Home >Backend Development >C++ >How to Implement JWT Bearer Token Authentication in ASP.NET Web API Hosted on IIS?
Implementing JWT Bearer token authentication in ASP.NET Web API hosted on IIS
Implementing JWT bearer token authentication in ASP.NET Web API hosted on IIS requires a different approach compared to .NET Core or OWIN applications. This article provides a comprehensive guide on how to implement this authentication mechanism and answers key questions:
How to generate JWT token?
To generate JWT tokens, you can use the System.IdentityModel.Tokens.Jwt NuGet package. Here is an example using HMACSHA256 and a symmetric key:
<code class="language-csharp">const string Secret = "db3OIsj+BXE9NZDy0t8W3TcNekrF+2d/1sFnWG4HnV8TZY30iTOdtVWJG8abWvB1GlOgJuQZdcF2Luqm/hccMw=="; 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>
How to provide JWT token?
A simple way is to create a token endpoint in the controller action:
<code class="language-csharp">public class TokenController : ApiController { [AllowAnonymous] public string Get(string username, string password) { if (CheckUser(username, password)) { return JwtManager.GenerateToken(username); } throw new HttpResponseException(HttpStatusCode.Unauthorized); } public bool CheckUser(string username, string password) { // 应该在数据库中检查 return true; } }</code>
How to verify JWT token?
Another approach is to create a JWTAuthenticationAttribute that inherits from IAuthenticationFilter:
<code class="language-csharp">private static bool ValidateToken(string token, out string username) { username = null; var simplePrinciple = JwtManager.GetPrincipal(token); var identity = simplePrinciple.Identity as ClaimsIdentity; if (identity == null || !identity.IsAuthenticated) return false; var usernameClaim = identity.FindFirst(ClaimTypes.Name); username = usernameClaim?.Value; if (string.IsNullOrEmpty(username)) return false; // 更多验证以检查系统中用户名是否存在 return true; } 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"); IPrincipal user = new ClaimsPrincipal(identity); return Task.FromResult(user); } return Task.FromResult<IPrincipal>(null); }</code>
This property can be applied to specific actions:
<code class="language-csharp">public class ValueController : ApiController { [JwtAuthentication] public string Get() { return "value"; } }</code>
Validate JWT token via middleware or DelegateHandler?
OWIN middleware or DelegateHandler can also be used to authenticate all incoming requests to the Web API.
Verify JWT token
The following code validates the JWT token and returns the body:
<code class="language-csharp">public static ClaimsPrincipal GetPrincipal(string token) { try { var tokenHandler = new JwtSecurityTokenHandler(); var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken; if (jwtToken == null) return null; var symmetricKey = Convert.FromBase64String(Secret); var validationParameters = new TokenValidationParameters() { RequireExpirationTime = true, ValidateIssuer = false, ValidateAudience = false, IssuerSigningKey = new SymmetricSecurityKey(symmetricKey) }; SecurityToken securityToken; var principal = tokenHandler.ValidateToken(token, validationParameters, out securityToken); return principal; } catch (Exception) { // 记录异常 return null; } }</code>
Authorization
Remember to add config.Filters.Add(new AuthorizeAttribute());
globally to prevent anonymous requests.
The above is the detailed content of How to Implement JWT Bearer Token Authentication in ASP.NET Web API Hosted on IIS?. For more information, please follow other related articles on the PHP Chinese website!