在ASP.NET Web API中实现JWT身份验证
JWT概述
JSON Web令牌(JWT)是包含声明的令牌,这些声明被编码为三个用句点分隔的base64编码部分。声明包含有关用户、其权限和过期时间的信息。
实现JWT身份验证
要在您的旧版Web API中实现JWT身份验证,您可以按照以下步骤操作:
生成JWT令牌
验证JWT令牌
配置
config.Filters.Add(new AuthorizeAttribute())
为您的API启用授权。代码示例
生成JWT令牌:
<code class="language-csharp">private const string Secret = "[对称密钥]"; public static string GenerateToken(string username, int expireMinutes = 20) { var symmetricKey = Convert.FromBase64String(Secret); var tokenHandler = new JwtSecurityTokenHandler(); var now = DateTime.UtcNow; var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }), Expires = now.AddMinutes(Convert.ToInt32(expireMinutes)), SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(symmetricKey), SecurityAlgorithms.HmacSha256Signature) }; var stoken = tokenHandler.CreateToken(tokenDescriptor); var token = tokenHandler.WriteToken(stoken); return token; }</code>
验证JWT令牌:
<code class="language-csharp">protected Task<IPrincipal> AuthenticateJwtToken(string token) { string username; if (ValidateToken(token, out username)) { var claims = new List<Claim> { new Claim(ClaimTypes.Name, username) // 根据需要添加更多声明 }; var identity = new ClaimsIdentity(claims, "Jwt"); var user = new ClaimsPrincipal(identity); return Task.FromResult(user); } return Task.FromResult<IPrincipal>(null); } private static bool ValidateToken(string token, out string username) { username = null; var tokenHandler = new JwtSecurityTokenHandler(); var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken; if (jwtToken == null) return false; var symmetricKey = Convert.FromBase64String(Secret); var validationParameters = new TokenValidationParameters { RequireExpirationTime = true, ValidateIssuer = false, ValidateAudience = false, IssuerSigningKey = new SymmetricSecurityKey(symmetricKey) }; var principal = tokenHandler.ValidateToken(token, validationParameters, out _); return principal != null; }</code>
以上是如何在 ASP.NET Web API 中实现 JWT 身份验证?的详细内容。更多信息请关注PHP中文网其他相关文章!