简体   繁体   English

Asp.Net Core 2.0 Cookie身份验证在时间之前到期

[英]Asp.Net Core 2.0 Cookie Authentication Expires Before Time

I have an MVC Asp.Net Core 2.0 application that uses Cookie Authentication. 我有一个使用Cookie身份验证的MVC Asp.Net Core 2.0应用程序。 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: ConfigureServices方法:

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 : 如果您使用的是2.0.x版本,请如下更改代码:

//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 顺便说一句, 2.0版本已在2018年10月1日终止生命。建议迁移到2.1.x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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