HttpContext.User.Identity.IsAuthenticated 为false

 

您可以通过手动设置HttpContext.User来实现此目的:

var identity = new ClaimsIdentity("Custom");

HttpContext.User = new ClaimsPrincipal(identity);

 

对于更复杂的东西,您可以添加如下声明:

var identity = new ClaimsIdentity(new List<Claim>
{
    new Claim("UserId", "123", ClaimValueTypes.Integer32)
}, "Custom");

HttpContext.User = new ClaimsPrincipal(identity);

这将导致:

HttpContext.User.Identity.IsAuthenticated == true;
int.Parse(((ClaimsIdentity)HttpContext.User.Identity).ValueFromType("UserId")) == 123;

 

获取identity信息

复制代码
        /// <summary>
        /// 当前用户ID
        /// </summary>
        public string UserId
        {
            get
            {
                if (IsAuthenticated && HttpContextAccessor.HttpContext.User.Claims.Any(s => s.Type == ClaimTypes.Name))
                {
                    var result = HttpContextAccessor.HttpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Name).Value;
                    return result;
                }
                else
                {
                    return "";
                }
            }
        }


        public IEnumerable<string> RoleKeys
        {
            get {
                if (!string.IsNullOrEmpty(UserId))
                {
                    return HttpContextAccessor.HttpContext.User.Claims.Where(c => c.Type == ClaimTypes.Role)?.Select(c => c.Value)?.ToList();
                }
                else {
                    return new List<string>();
                }
            }
        }

        public IEnumerable<string> RoleIds
        {
            get
            {
                var result=new List<string>();
                if (!string.IsNullOrEmpty(UserId))
                {
                    var roleIds = HttpContextAccessor.HttpContext.User.Claims.SingleOrDefault(c => c.Type == "RoleIds")?.Value;
                    if (!string.IsNullOrEmpty(roleIds))
                    {
                        result= roleIds.Split(',').ToList();
                    }
                }
                return result;
            }
        }
复制代码

 

 

https://cloud.tencent.com/developer/ask/sof/290519

posted @   BloggerSb  阅读(139)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2019-04-18 C# C/S程序出错:ContextSwitchDeadlock is detected
2016-04-18 301重定向
点击右上角即可分享
微信分享提示