Modern distributed applications often require more robust authentication than traditional ASP.NET Web API methods like forms or Windows authentication. This guide details implementing JWT bearer token authentication in a Web API hosted on IIS.
1. Token Generation
A JWT token comprises a header, claims, and signature. The System.IdentityModel.Tokens.Jwt
NuGet package facilitates token generation using HMACSHA256 with a symmetric key.
public static string GenerateToken(string username, int expireMinutes = 20) { var symmetricKey = Convert.FromBase64String(Secret); var tokenHandler = new JwtSecurityTokenHandler(); ... return token; }
2. Token Validation
Token validation is achieved using:
private static bool ValidateToken(string token, out string username) { ... }
This forms the core of a custom authentication filter attribute:
public class JwtAuthenticationAttribute : Attribute, IAuthenticationFilter { ... }
3. Request Authentication
Apply the JwtAuthenticationAttribute
to actions or routes requiring authentication. The filter validates the JWT and provides a ClaimsPrincipal
(or null on failure).
4. Authorization
Employ the AuthorizeAttribute
globally to restrict anonymous access. Within secured actions, retrieve user details from the ClaimsPrincipal
.
This method enables JWT bearer token authentication in your IIS-hosted ASP.NET Web API without OWIN middleware, offering secure and scalable authorization for your web services.
The above is the detailed content of How to Implement JWT Bearer Token Authentication in ASP.NET Web API on IIS?. For more information, please follow other related articles on the PHP Chinese website!