Home >Backend Development >C++ >How to Implement JWT Authentication in ASP.NET Web API?
Implementing JWT Authentication in ASP.NET Web API
JWT Overview
A JSON Web Token (JWT) is a token that contains claims encoded into three base64-encoded parts separated by periods. The claim contains information about the user, their permissions, and expiration time.
Implementing JWT authentication
To implement JWT authentication in your legacy Web API, you can follow these steps:
Generate JWT token
Verify JWT token
Configuration
config.Filters.Add(new AuthorizeAttribute())
to enable authorization for your API. Code Example
Generate JWT token:
<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>
Verify JWT token:
<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>
The above is the detailed content of How to Implement JWT Authentication in ASP.NET Web API?. For more information, please follow other related articles on the PHP Chinese website!