0

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?

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

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

2 Comments

I try your code, it working for first time. When i try again for 3 and 5 minutes, it not working.
Could you share your Startup.cs and you detailed LoginController?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.