HttpContext.User.Identity.IsAuthenticated 為false

BloggerSb發表於2024-04-18

您可以透過手動設定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

相關文章