.NetCore3.1 使用JWT认证授权时获取当前请求的用户名

在netcore5.0里,这样不行了

应该编入用户名,最后用HttpContext.User.Identity获取(从claim获取)

//======================================================================================================================================================================

最近使用JWT来给WebApi进行授权认证,在项目中使用 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

 
 
原文地址:https://www.cnblogs.com/qqhfeng/p/14208111.html