最近使用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