saf21
saf21

Reputation: 844

Session Timeout not expired

Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDistributedMemoryCache();

        // session will destroy after idle for 1 minutes
        services.AddSession(options => {
            options.IdleTimeout = TimeSpan.FromMinutes(1);
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
        });

        // add authentication
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(
            CookieAuthenticationDefaults.AuthenticationScheme,
            options =>
            {
                options.LoginPath = new PathString("/");
                options.Cookie.Expiration = TimeSpan.FromMinutes(1);
                //options.AccessDeniedPath = new PathString("/auth/denied");
            });

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

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        // add use authentication
        app.UseAuthentication();
        app.UseSession();

        app.UseStatusCodePagesWithRedirects("/Error/{0}");

        app.UseStaticHttpContext();

        app.UseMvc(routes =>
        {
            // routes
            ...
        });
    }

LoginController.cs

[HttpPost]
[Route("Login")]
public IActionResult Login(LoginModel model)
{
    var claims = new List<Claim> {
        // create claim
        ...
    };

    var userIdentity = new ClaimsIdentity(claims, "SecureLogin");
    var userPrincipal = new ClaimsPrincipal(userIdentity);

    HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
    userPrincipal,
    new AuthenticationProperties
      {
        IssuedUtc = DateTime.UtcNow,
        IsPersistent = false,
        AllowRefresh = false
      });
}

Above is my code to set a session and login for my application. You can see in Startup.cs, I set session expiry to 1 minutes.

options.IdleTimeout = TimeSpan.FromMinutes(1);

options.Cookie.Expiration = TimeSpan.FromMinutes(1);

But its not working, I already login since yesterday but the session still exist and alive now. Can someone help me?

Upvotes: 0

Views: 2980

Answers (2)

Rena
Rena

Reputation: 36615

Try this:

services.ConfigureApplicationCookie(options =>
{
        options.ExpireTimeSpan = TimeSpan.FromMinutes(1);
});

Upvotes: 0

saf21
saf21

Reputation: 844

Here is my solutions.

[HttpPost]
[Route("Login")]
public IActionResult Login(LoginModel model)
{
  var claims = new List<Claim> {
    // create claim
    ...
  };

  var userIdentity = new ClaimsIdentity(claims, "SecureLogin");
  var userPrincipal = new ClaimsPrincipal(userIdentity);

  HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
  userPrincipal,
  new AuthenticationProperties
  {
    IssuedUtc = DateTime.UtcNow,
    IsPersistent = false,
    ExpiresUtc = DateTime.UtcNow.AddMinutes(1)
  });
}

I add below code to the login controller. Now when user idle for 1 minutes, it will auto logout.

ExpiresUtc = DateTime.UtcNow.AddMinutes(1)

Upvotes: 2

Related Questions