.NetCore3.1 使用JWT認證授權時獲取當前請求的用戶名


最近使用JWT來給WebApi進行授權認證,在項目中使用 Response.HttpContext.User.Identity.Name 獲取當前登錄的用戶名一直獲取不到,以往都是這樣獲取,這個問題查了很久都沒找到相關資料

特此記錄一下,避坑。

在JWT生成Token時一定要加入ClaimTypes.Name這樣才能獲取到用戶名

 

public static string GetToken(string userName)
        {
            var claims = new List<Claim>();
            claims.AddRange(new[] {
                new Claim(ClaimTypes.Name, userName),
                new Claim(JwtRegisteredClaimNames.Sub, userName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.Now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
            });
            var tokenManagement = UtilConfHelper.GetTokenManagement();
            DateTime now = DateTime.Now;
            var jwtSecurityToken = new JwtSecurityToken(
                issuer: tokenManagement.Issuer,
                audience: tokenManagement.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(TimeSpan.FromMinutes(tokenManagement.AccessExpiration)),
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(tokenManagement.Secret)), SecurityAlgorithms.HmacSha256)
            );
            string token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            return token;
        }

 

 獲取就使用 Response.HttpContext.User.Identity.Name 獲取userName


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM