.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