Home > Software design >  JWT Token doesn't want to expire
JWT Token doesn't want to expire

Time:03-09

My session is not expiring after use of authentication despite expiration time being set to 1 minute. Let me show you my code

JWT Token generator

            var claims = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.UserName)
                });
            var key = Encoding.UTF8.GetBytes(_jwtSettings.Secret);
            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = claims,
                Expires = DateTime.Now.AddMinutes(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            return tokenHandler.WriteToken(token);

Identiy configuration in Startup.cs

            services.AddIdentity<ApplicationUser, IdentityRole>(
                options =>
                {
                    options.SignIn.RequireConfirmedAccount = true;
                    options.Password.RequireDigit = true;
                    options.Password.RequireLowercase = true;
                    options.Password.RequireNonAlphanumeric = false;
                    options.Password.RequireUppercase = true;
                    options.Password.RequiredLength = 6;
                    options.Password.RequiredUniqueChars = 1;
                }
                )
                .AddEntityFrameworkStores<AppDbContext>()
                .AddDefaultTokenProviders();

            var jwtSettings = GetJwtSettings(configuration);
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.RequireHttpsMetadata = false;
                    options.SaveToken = true;
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Secret)),
                        ValidateIssuer = false,
                        ValidateAudience = false,
                        ValidateLifetime = true,
                        ClockSkew = TimeSpan.Zero
                    };
                });

Pipeline in Program.cs

var app = builder.Build();
app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

I use this kind of code to sign in

await _signInManager.PasswordSignInAsync(existingUser, request.Password, true, false);

My controller

        [HttpGet]
        public async Task<IActionResult> GetIsAuthenticated()
        {
            return Ok(User.Identity.IsAuthenticated);
        }

        [HttpGet("test")]
        [Authorize]
        public async Task<IActionResult> GetTest()
        {
            return Ok("OK");
        }

Calling GetIsAuthenticated and GetTest methods in api using Swagger and no formerly logging return respectively False and 404 Error. And then if I sign in with fully functioning user credentials using methods above I get True and OK responses. Thats great and what I really need.

But the problem is, after few minutes token/session is still active(reminding I it set to 1 minute). I can wait even hour and respond from the methods are still the same... My code is not extraordinary so what is going on?

CodePudding user response:

I had to implement JWT Bearer in Swagger configuration. It works now.

CodePudding user response:

You can refer to this code:

private string GerarTokenJWT()
        {
            var issuer = _config["Jwt:Issuer"];
            var audience = _config["Jwt:Audience"];
            var expiry = DateTime.Now.AddMinutes(1);
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(issuer: issuer, audience: audience,
expires: expiry, signingCredentials: credentials);
            var tokenHandler = new JwtSecurityTokenHandler();
            var stringToken = tokenHandler.WriteToken(token);
            return stringToken;
        }

The specific demonstration effect can be seen in this post:

Swagger verification authority

  • Related