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 @ 2024-04-18 00:24  BloggerSb  阅读(78)  评论(0编辑  收藏  举报