1

我知道这个话题在这里可能有一些重复的问题,但我仍然感到困惑。我对Thread.CurrentPrincipal.IdentityHttpContext.Current.User.Identity有一个非常奇怪的情况。

我有一个 userIdentity.cs 类,我依赖于从我的令牌中获取当前活动用户。最初我的应用程序是托管在 IIS 上的 2 个单独虚拟机上的 MVC 应用程序。我使用Thread.CurrentPrincipal.Identity从令牌声明中检索当前用户,我没有遇到任何问题。但是,我已经更新了代码以与内置的 SPA 应用程序兼容。更新后,Thread.CurrentPrincipal.Identity不再工作,所以我不得不做一个后备计划并调用HttpContext.Current.User.Identity来检索索赔。所以用户身份类更新为如下:

 public class UserIdentity : IUserIdentity
    {
        private IIdentity _identity;

        public UserIdentity()
        {
            _identity = null;
            _identity = InitializeClaimsIdentity();
        }

        private ClaimsIdentity InitializeClaimsIdentity()
        {
            return Thread.CurrentPrincipal?.Identity != null ?
                     Thread.CurrentPrincipal.Identity as ClaimsIdentity :
                        HttpContext.Current.User.Identity as ClaimsIdentity;  //HttpContext.Current.User.Identity used for Main SPA
        }

        public string GetUserId()
        {
            var userId = GetClaimsIdentity().FindFirst("username")?.Value;
            userId = string.IsNullOrEmpty(userId) ? GetClaimsIdentity(forceInit: true).FindFirst("username")?.Value : userId;
            return userId;
        }

        public ClaimsIdentity GetClaimsIdentity(bool forceInit = false)
        {
            if (_identity == null || forceInit)
            {
                _identity = InitializeClaimsIdentity();
            }
            return (ClaimsIdentity)_identity;
        }
    }

该解决方案在开发环境(在 MVC 和 SPA 上)上完美运行。

然而,在将此解决方案部署到生产环境后,MVC 托管在 2 个虚拟机上,同时拥有大量用户,索赔开始以错误的方式返回。用户 ID 搞砸了,返回了错误的数据。在调试它时,我无法重现该案例。当删除HttpContext.Current.User.Identity 作为 ClaimsIdentity作为后备解决方案时,事情就像一个魅力;

如果有人可以向我解释 Thread.CurrentPrincipal 和 Current.User 之间的主要区别,那就太好了。

另外,如何正确实现与 MVC 兼容的解决方案并响应 SPA 应用程序?

抱歉发了这么长的帖子,提前谢谢你,

4

0 回答 0