简体   繁体   中英

Asp.Net Core 2.0 Cookie Authentication Expires Before Time

I have an MVC Asp.Net Core 2.0 application that uses Cookie Authentication. The problem is that the session expires ahead of time and redirects the user to the login path, forcing him to authenticate again.

My Startup Class:

ConfigureServices Method:

const string schema = "adminScheme";

services.AddAuthentication(schema).AddCookie(schema, options =>
{
    options.AccessDeniedPath = new PathString("/Account/AcessoNegado");
    options.Cookie = new CookieBuilder
    {
        HttpOnly = true,
        Name = ".Admin.Security.Cookie",
        Path = "/",
        SameSite = SameSiteMode.Lax,
        SecurePolicy = CookieSecurePolicy.SameAsRequest
    };
    options.ExpireTimeSpan = TimeSpan.FromMinutes(480);
    options.LoginPath = new PathString("/Account/Login");
    options.LogoutPath = new PathString("/Account/Logout");
    options.ReturnUrlParameter = "RequestPath";
    options.SlidingExpiration = true;
});

on Configure Method:

 app.UseAuthentication();

My Login Method:

var cadastro = user.FirstOrDefault();
const string Issuer = "adminScheme";

List<Claim> claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, cadastro.NomeUsuario, ClaimValueTypes.String, Issuer),
    new Claim("Idusuario",cadastro.Id.ToString(), ClaimValueTypes.String, Issuer),
    new Claim("IdtipoUsuario", cadastro.IdtipoUsuario.ToString(), ClaimValueTypes.String, Issuer)
};

ClaimsIdentity identity = new ClaimsIdentity(claims, "cookie");

ClaimsPrincipal principal = new ClaimsPrincipal(identity);

await HttpContext.SignInAsync(scheme: Issuer,
        principal: principal,
        properties: new AuthenticationProperties
        {
            IsPersistent = true,
            ExpiresUtc = DateTime.UtcNow.AddMinutes(480)
        });

return RedirectToLocal(returnUrl);

And I use the [Authorize] In My Controllers.

I just tried your code. If you're using the 2.0.x version, change your code as below :

//ClaimsIdentity identity = new ClaimsIdentity(claims, "cookie");
ClaimsIdentity identity = new ClaimsIdentity(claims, "adminScheme");

And now it works flawlessly for me.

By the way, the version of 2.0 has already reached end of life on October 1, 2018. It is suggested to migrate to 2.1.x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM