0

This is an asp.net core web app on .net 5 using Identity framework. I use two authentication schemes Cookie and Jwt. Both are configure as below.

services.AddIdentity() with below options

  • Password.RequiredLength
  • User.AllowedUserNameCharacters
  • User.RequireUniqueEmail

Then I use:

services.ConfigureApplicationCookie() with below options

  • options.Cookie.HttpOnly = true;
  • options.Cookie.SameSite = SameSiteMode.Lax;
  • options.Cookie.IsEssential = true;
  • options.Cookie.Expiration = TimeSpan.FromMinutes(60);
  • options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
  • options.SlidingExpiration = true;

Then I also have

services.AddAuthentication().AddJwtBearer() with below options

  • options.SaveToken = true;
  • options.TokenValidationParameters (…)

In the login, I have:

var props = new AuthenticationProperties
{
     AllowRefresh = true,
     ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(CommonServices.Configuration.GetValue("JWT:Lifetime", 60)),
     IsPersistent = true,
                
};

await _signInManager.SignInWithClaimsAsync(user, props, claims.Data);

Apart from above, once user is authenticated, I create a JWT token as well. I want my JwtToken and cookie to have same expire time. Currently JWT token expiration works fine and honors the set time. But cookie doesn't seem to honor the settings I have set in ConfigureApplicationCookie(). It kicks the user out before the set time.

If I check the ".AspNetCore.Identity.Application" cookie in devtools it shows the expire time in UTC properly as expected, but still user gets logged out before this time. So, something within the cookie may be having wrong information and I can't figure out what that is.

I referred to below questions which are similar but for previous versions and Couldn’t find a good explanation about what I am doing wrong.

ASP.NET Core MVC: setting expiration of identity cookie - Stack Overflow

c# - Why User.Identity.IsAuthenticated setting to false after some time in Identity Cookie based authentication - Stack Overflow

c# - if (!context.HttpContext.User.Identity.IsAuthenticated) always returns false is there any way to make it has true - Stack Overflow

user2058413
  • 691
  • 3
  • 10
  • 28
  • The code you provided seems correct, but I need more details about the order in startup.cs file. [And you also can refer this answer, maybe it can help you](https://stackoverflow.com/a/49020842/7687666). – Jason Pan Jul 26 '22 at 07:42

0 Answers0