JWT Token Expiration and Authorization

Ronald Rex 1,666 Reputation points
2022-05-11T17:15:23.547+00:00

I am working with a JWT in .Net Core 6.0 Web Api. I am struggling with JWT expiration time...not sure if it is being set correctly with the UTC being different from my loacl time. But I also am having an issue with not being able to run an API Method after I Annotate the Method with [Authorize], even though I generate a token and send it with the request in postman. Really odd behavior with the JWT and expiration. Thanks for any help !!!

Developer technologies .NET Entity Framework Core
Developer technologies ASP.NET ASP.NET Core
Microsoft Security Microsoft Identity Manager
{count} votes

Accepted answer
  1. AgaveJoe 30,126 Reputation points
    2022-05-12T11:13:11.483+00:00

    I noticed the configuration sets issuer and audience validation but the login action does not set these values.

                         x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                         {
                             ValidateIssuerSigningKey = true,
                             IssuerSigningKey = new SymmetricSecurityKey(key),
                             ValidateIssuer = true,
                             ValidateAudience = true,
                             ValidateLifetime = true,
                             ClockSkew = TimeSpan.Zero
                         };
    

    Either set the configuration values to false or add the issuer and audience claims to the token.

    public string Authenticate(string username, string password)
    {
        var user = _users.SingleOrDefault(x => x.Username == username && x.Password == password);
    
        // return null if user not found
        if (user == null)
            return null;
    
        // authentication successful so generate jwt token
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(Configuration["JwtConfig:secret"]);
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.Name, user.Id.ToString()),
            }),
            IssuedAt = DateTime.UtcNow,
            Expires = DateTime.UtcNow.AddMinutes(10),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
            Issuer = "Issuer",
            Audience = "Audience"
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    }
    
    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-05-11T21:00:00.793+00:00

    typically an access token is good for 60 minutes. does the token have the scope to call the method? it a valid access token or an id token?

    0 comments No comments

  2. Anonymous
    2022-05-12T02:44:12.287+00:00

    Hi @Ronald Rex ,

    The expire time for the token is generated when you are using the token generated codes. Since we don't know how you generate that token, if you write the JWT token generation by yourself, I suggest you could try to modify the expires property like below:

                var token = new JwtSecurityToken(configuration["Jwt:Issuer"], configuration["Jwt:Issuer"],   
                                null, expires: DateTime.Now.AddMinutes(60),  
                                signingCredentials: credentials); //60mins expiration   
    

    More details, you could refer to JwtSecurityToken Constructors.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.