JWT expires too fast in .NET Core Web API

487 Views Asked by At

I'm facing a problem where my JWT expires within a few minutes after idling, even after I've set the ExpireTimeSpan to 60 minutes (or longer; even tried 1 year).

Currently the way I'm keeping the token from being expired is to send dummy requests to my server at a few minutes interval, which actually do trigger the SlidingExpiration part.

Ideally I would like to keep the token alive even after a user closes my web page. I'm not sure what I've missed in my startup code, any pointers?

services.AddAuthentication(a =>
{
    a.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    a.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
    string secretKeyStr = Configuration.GetValue<string>("SecretKey");
    byte[] secretKey = null;

    if (secretKeyStr != null)
        secretKey = Encoding.ASCII.GetBytes(secretKeyStr);

    x.RequireHttpsMetadata = false;
    x.SaveToken = true;
    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(secretKey),
        ValidateIssuer = false,// validate the server that generates the token
        ValidateAudience = false,//validate the user who generates token is authorized
        RequireExpirationTime = true,
        ValidateLifetime = true,
        ClockSkew = TimeSpan.FromDays(1),
    };
}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.ExpireTimeSpan = TimeSpan.FromMinutes(60); });

services.Configure<CookiePolicyOptions>(options =>
{
    options.CheckConsentNeeded = context => false;
    options.MinimumSameSitePolicy = SameSiteMode.None;
});

services.AddDistributedMemoryCache();

services.AddSession(options =>
{
    options.Cookie.SameSite = SameSiteMode.None;
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    options.Cookie.IsEssential = true;
    options.IdleTimeout = TimeSpan.FromMinutes(60);
    options.Cookie.HttpOnly = true;
});

services.ConfigureApplicationCookie(options =>
{
    options.SlidingExpiration = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
});

Edit : Here's how I generate my token.

var JWToken = new JwtSecurityToken(
                issuer: Configuration.GetValue<string>("my_issuer"),
                audience: Configuration.GetValue<string>("my_audience"),
                claims: GetUserClaims(user),
                notBefore: new DateTimeOffset(DateTime.Now).DateTime,
                expires: DateTime.UtcNow.AddYears(1),
                //Using HS256 Algorithm to encrypt Token
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey(secretKey),
                                    SecurityAlgorithms.HmacSha256Signature)
            );
            var token = new JwtSecurityTokenHandler().WriteToken(JWToken);
1

There are 1 best solutions below

3
On BEST ANSWER

Can you try to create token like this

        var tokenHandler = new JwtSecurityTokenHandler();
        var tokenDescriptor = new SecurityTokenDescriptor
        {
          
            Subject = new ClaimsIdentity(GetUserClaims(user)),
            Expires = DateTime.UtcNow.AddYears(1),
            Issuer = Configuration.GetValue<string>("my_issuer"),
            Audience =Configuration.GetValue<string>("my_audience"),
            SigningCredentials = new SigningCredentials(mySecurityKey, SecurityAlgorithms.HmacSha256Signature),
            NotBefore=new DateTimeOffset(DateTime.Now).DateTime
        };

        var tkn = tokenHandler.CreateToken(tokenDescriptor);
        var token= tokenHandler.WriteToken(tkn);