我有一个 ASP.NET Core 站点,使用 AspNetCore.Identity.EntityFrameworkCore 1.1.1 和 cookie 来授权/验证我的用户。无论我在下面的代码中选择什么设置,cookie 都会在大约 20 分钟后过期,我不明白为什么。除非您关闭浏览器并清除历史记录/cookie,否则该网站将不再工作。有什么想法吗?
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,
});
我还有一些 razor 代码,用于控制是否在 _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();
另外,请看一下https://stackoverflow.com/a/34981457/1137785,它提供了此类场景的背景并提供了非常好的解释。
我认为问题在于我将数据保存到具有不同设置的 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);
我个人使用这种方式是为了以后使用SignInManager:
builder.Services.AddDbContext<Server04DbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("Local"));
}).AddIdentity<AppUser, IdentityRole>(options =>
{
options.SignIn.RequireConfirmedEmail = false;
options.User.RequireUniqueEmail = false;
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyz0123456789";
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(10);
options.Password.RequireNonAlphanumeric = false;
options.Password.RequiredLength = 4;
}).AddDefaultTokenProviders().AddEntityFrameworkStores<Server04DbContext>();
builder.Services.ConfigureApplicationCookie(options =>
{
options.LoginPath = new PathString("/Auth/Login");
options.LogoutPath = new PathString("/Auth/Logout");
options.AccessDeniedPath = new PathString("/Home/AccessDenied");
options.Cookie = new()
{
Name = "IdentityCookie",
HttpOnly = true,
SameSite = SameSiteMode.Lax,
SecurePolicy = CookieSecurePolicy.Always
};
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromDays(30);
});