小编Iva*_*.Yu的帖子

如何设置asp.net标识cookie到期时间

我使用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
    });
}
Run Code Online (Sandbox Code Playgroud)

和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);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我发现当用户没有选择isPersistent复选框时,cookies的到期日期已经是"会话",而不是当前时间加上30分钟.

在此输入图像描述

使用像之后的代码时的cookie状态,所以'记住我'复选框无法正常工作.:(.

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            ExpireTimeSpan = …
Run Code Online (Sandbox Code Playgroud)

c# asp.net cookies asp.net-identity

25
推荐指数
3
解决办法
3万
查看次数

标签 统计

asp.net ×1

asp.net-identity ×1

c# ×1

cookies ×1