Home >Backend Development >C++ >How to Implement JWT Authentication in ASP.NET Web API?

How to Implement JWT Authentication in ASP.NET Web API?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-20 21:59:12752browse

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

  • Create a JWT generation endpoint using a controller action.
  • Use the System.IdentityModel.Tokens.Jwt package to generate JWT tokens using HMACSHA256 and symmetric keys.

Verify JWT token

  • Create a JWT authentication attribute inherited from IAuthenticationFilter.
  • Use this attribute to decorate operations that require authentication.
  • Implement the AuthenticateJwtToken method in your authentication filter to verify the JWT token.
  • Use a verified ClaimsPrincipal to create a local identity with additional information such as roles.

Configuration

  • Use 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn