【问题标题】:Asp.Net Core 2.0 Cookie Authentication Expires Before TimeAsp.Net Core 2.0 Cookie 身份验证提前过期
【发布时间】:2019-04-19 23:12:24
【问题描述】:

我有一个使用 Cookie 身份验证的 MVC Asp.Net Core 2.0 应用程序。问题是会话提前过期并将用户重定向到登录路径,迫使他再次进行身份验证。

我的创业班:

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;
});

关于配置方法:

 app.UseAuthentication();

我的登录方式:

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);

我在我的控制器中使用 [Authorize]。

【问题讨论】:

    标签: c# authentication asp.net-core-2.0 session-cookies


    【解决方案1】:

    我刚刚尝试了您的代码。如果您使用的是2.0.x 版本,请将您的代码更改如下:

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

    现在它对我来说完美无缺。

    顺便说一句,2.0的版本已经在2018年10月1日结束,建议迁移到2.1.x

    【讨论】:

      猜你喜欢
      • 2018-09-29
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 2018-02-17
      • 1970-01-01
      • 2018-07-19
      相关资源
      最近更新 更多