ASP.NET 核心身份和 Cookie

ASP.NET Core Identity & Cookies

我有一个 ASP.NET 核心站点,使用 AspNetCore.Identity.EntityFrameworkCore 1.1.1 和 authorize/authenticate 我的用户的 cookie。无论我在下面的代码中选择什么设置,cookie 都会在大约 20 分钟后过期,我不知道为什么。除非您关闭浏览器并清除 history/cookies,否则该网站将不再工作。有什么想法吗?

services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
    //  Require a confirmed email in order to log in
    config.SignIn.RequireConfirmedEmail = true;
})
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

app.UseIdentity();

//  Add cookie middleware to the configure an identity request and persist it to a cookie.
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationScheme = "Cookie",
    LoginPath = new PathString("/Account/Login/"),
    AccessDeniedPath = new PathString("/Account/Forbidden/"),
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    ExpireTimeSpan = TimeSpan.FromMinutes(20),
    SlidingExpiration = true,

});

我还有一些剃须刀代码可以控制是否在 _layout 页面上显示管理菜单。当 cookie 过期时,这会崩溃,因为用户突然没有声明。有没有更好的方法来处理这个问题?

// If user is admin then show drop down with admin navigation
@if (User.HasClaim(System.Security.Claims.ClaimTypes.Role, "admin"))
{
    <ul class="nav navbar-nav">
        @*etc*@
    </ul>
}

当您使用 ASPNET 标识时,您不需要单独的 CookieAuthentication 中间件。 UseIdentity() 将为您执行此操作并生成一个 cookie。您可以像这样在应用程序的 AddIdentity 块中设置 "cookie options"

     services.AddIdentity<ApplicationUser, IdentityRole>(config =>
            {
                //  Require a confirmed email in order to log in
                config.SignIn.RequireConfirmedEmail = true;

               // Your Cookie settings
              config.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(1);
              config.Cookies.ApplicationCookie.LoginPath = "/Account/LogIn";
              config.Cookies.ApplicationCookie.LogoutPath = "/Account/LogOut";
            }).AddEntityFrameworkStores<ApplicationDbContext().AddDefaultTokenProviders();

另外,看看,它给出了这种场景的背景,并有很好的解释。

我认为问题在于我将数据保存到具有不同设置的 cookie。

不确定这是否是正确的方法,但我可以通过使用 services.AddIdentity 和 app.UseCookieAuthentication 解决问题,如下所示。

在 ConfigureServices 中,设置用于登录的 cookie:

        //  set the cookie for sign in
        services.AddIdentity<ApplicationUser, IdentityRole>(config =>
        {               
            //  Require a confirmed email in order to log in
            config.SignIn.RequireConfirmedEmail = true;
            // Cookie settings
            config.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromHours(10);
            config.Cookies.ApplicationCookie.LoginPath = "/Account/LogIn";
            config.Cookies.ApplicationCookie.LogoutPath = "/Account/LogOut";
        }).AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();

在配置中设置用于保留声明的 cookie 方案:

        //  Add cookie middleware to the configure an identity request and persist it to a cookie.
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationScheme = "Cookie",
            LoginPath = new PathString("/Account/Login/"),
            AccessDeniedPath = new PathString("/Account/Forbidden/"),
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            //ExpireTimeSpan = TimeSpan.FromSeconds(10),
            ExpireTimeSpan = TimeSpan.FromHours(10),
            SlidingExpiration = true,
        });

在登录方法中,坚持声明:

await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal);