【问题标题】:Expired time doesn't work in ASP.Net Core过期时间在 ASP.Net Core 中不起作用
【发布时间】:2018-12-18 03:26:46
【问题描述】:

https://github.com/NanaseRuri/LibraryDemo/tree/Failed

我已经在我的 ASP.Net Core 项目中设置了过期时间,但它不起作用。 8 秒后,我仍然可以使用 [Authorize] 输入操作。

await HttpContext.SignInAsync(principal,new AuthenticationProperties()
{
    ExpiresUtc = DateTime.UtcNow.AddSeconds(8)
});

Startup.cs:

services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
});

身份验证:

if (admin.Password == encryptedPassword)
{
    ClaimsIdentity identity = new ClaimsIdentity("Cookie");
    identity.AddClaims(new[]
    {
        new Claim(ClaimTypes.Name, admin.UserName),
        new Claim(ClaimTypes.Email, admin.Email),
        new Claim(ClaimTypes.MobilePhone, admin.PhoneNumber),
        new Claim(ClaimTypes.Role, "admin"),
    });

    var principal = new ClaimsPrincipal(identity);
    await HttpContext.SignInAsync(principal, new AuthenticationProperties()
    {
        ExpiresUtc = DateTime.UtcNow.AddSeconds(8)
    });

    if (returnUrl != null)
    {
        return Redirect(returnUrl);
    }

    return RedirectToAction("Index");
}

【问题讨论】:

    标签: authentication cookies asp.net-core authorization


    【解决方案1】:

    请尝试以下方法!我已经对此进行了测试,并且效果很好。

    services.ConfigureApplicationCookie(options =>
    {
        // Cookie settings
        options.Cookie.HttpOnly = true;
        options.ExpireTimeSpan = TimeSpan.FromMinutes(5); // Set your expiration time here
    
    
        options.SlidingExpiration = false;
    });
    

    只要登录用户处于活动状态,如果您不希望过期,请创建 options.SlidingExpiration = true;

    【讨论】:

    • 谢谢!帮助很大!似乎身份框架将 Cookie.HttpOnly 设置为 false。
    • @NanaseRuri 这不是问题。 options.Cookie.HttpOnly = true; 是为了安全。过期时间与options.ExpireTimeSpan = TimeSpan.FromMinutes(5);有关
    • 是的,我的问题完美解决了!我只是混淆了 Microsoft 文档中不存在代码--options.Cookie.HttpOnly = true 。 docs.microsoft.com/en-us/aspnet/core/security/authentication/…
    • 很高兴听到这个消息!谢谢。
    猜你喜欢
    • 1970-01-01
    • 2018-12-22
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    相关资源
    最近更新 更多