Home > Software engineering >  ASP.NET Core Web API : JWT token validation with Gmail provider
ASP.NET Core Web API : JWT token validation with Gmail provider

Time:02-05

I have a NextJS front end that uses Gmail for authentication and gets the user's information from the ID token, which is a JWT token. ASP.nET Core Web API gets this ID token.

Now, how do you validate the token in ASP.NET Core and get the claims from the token?

CodePudding user response:

You can validate the JWT token in ASP.NET Core using the Microsoft.IdentityModel.Tokens library. Here is the code:

public int? ValidateToken(string token)
{
    if (token == null) 
        return null;

    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
    try
    {
        tokenHandler.ValidateToken(token, new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false,
            // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
            ClockSkew = TimeSpan.Zero
        }, out SecurityToken validatedToken);

        var jwtToken = (JwtSecurityToken)validatedToken;
        var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "id").Value);

        // return user id from JWT token if validation successful
        return userId;
    }
    catch
    {
        // return null if validation fails
        return null;
    }
}
  • Related