我使用Asp.Net Identity来控制我的应用程序的授权。现在,我需要做到这一点:如果用户在30分钟内没有操作,则跳转到登录页面,当他登录时不选中“isPersistent”复选框。 而且,如果他选中了“isPersistent”复选框,则将cookie的过期日期设置为14天。 我尝试通过更改Startup.Auth.cs文件来实现这一点:
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
SlidingExpiration = true,
CookieName = WebHelpers.ConstStrings.AUTHCOOKIESNAME
});
}
并且 SignIn 代码看起来像这样:
private async Task SignInAsync(User user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
if (isPersistent)
{
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
else
{
AuthenticationManager.SignIn(new AuthenticationProperties() { ExpiresUtc = new DateTimeOffset(DateTime.UtcNow.AddMinutes(30)) }, identity);
}
}
但是我发现当用户不选择isPersistent复选框时,cookie的过期日期已经是“Session”,而不是当前时间加30分钟。
使用以下代码后,cookie状态为如下,因此“记住我”复选框无法工作。:(
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
ExpireTimeSpan = TimeSpan.FromMinutes(30),
SlidingExpiration = true,
CookieName = WebHelpers.ConstStrings.AUTHCOOKIESNAME
});
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, isPersistent: false, shouldLockout: false);
,没有ExpiresUtc
或其他任何可设置的方式。 - empz