【发布时间】:2021-04-22 23:24:30
【问题描述】:
我开始使用 ASP.Net Core 2.2 开发网站。 我正在通过自定义 cookie 身份验证(不是身份)实现登录/注销。
请查看或克隆the repo:
git clone https://github.com/mrmowji/aspcore-custom-cookie-authentication.git .
...或者阅读下面的代码sn-ps。
这是Startup.cs中的代码:
public void ConfigureServices(IServiceCollection services) {
...
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => {
options.LoginPath = new PathString("/login");
options.ExpireTimeSpan = TimeSpan.FromDays(30);
options.Cookie.Expiration = TimeSpan.FromDays(30);
options.SlidingExpiration = true;
});
...
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
...
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
...
这是Login操作的代码:
public async Task<IActionResult> Login(LoginViewModel userToLogin) {
var username = "username"; // just to test
var password = "password"; // just to test
if (userToLogin.UserName == username && userToLogin.Password == password) {
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, "admin"),
new Claim(ClaimTypes.Role, "Administrator"),
};
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties {
AllowRefresh = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddDays(10),
IsPersistent = true,
};
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
...
Cookie 已按预期设置。我有一个.AspNetCore.Cookies cookie,有效期为 10 天后。但大约 30 分钟后,用户退出。即使关闭浏览器,如何强制认证用户保持登录状态?
【问题讨论】:
-
@LeonardoSeccia 我没有检查。他/她必须这样做吗?
-
您可能将
IdleTimeout设置为 30 分钟...无论哪种方式。你也可以分享你的ValidatePrincipal方法吗(如果你已经覆盖了它)? -
@LeonardoSeccia 我没有。我在论坛中没有看到任何关于
ValidatePrincipal的建议解决方案或 tut 这种类型的身份验证。我应该实施吗? -
另一个想法...您的服务器是否永久存储 cookie 解密密钥?如果没有,每当服务器或应用程序池重新启动时,用户将不得不再次登录......
-
你能把它归结为minimal reproducible example吗?
标签: c# authentication asp.net-core cookie-authentication