首页 > 解决方案 > Cookie 持久性在 OWIN 身份验证中不起作用

问题描述

我正在开发一个使用 OWIN 身份验证系统(Microsoft.Owin v4.1.0通过 NuGet)的 MVC5 网站。我根据数据库验证用户的登录凭据,然后使用 OWINIAuthenticationManager登录。以下是相关代码:

using Microsoft.Owin.Security;

public class AuthManager : IAuthManager
{
    private readonly IAuthenticationManager AuthenticationManager;

    public AuthManager()
    {
        this.AuthenticationManager = HttpContext.Current.GetOwinContext().Authentication;
    }

    public void SignIn(AppUserState appUserState, bool rememberMe)
    {
        AuthenticationProperties authenticationProperties = new AuthenticationProperties()
        {
            AllowRefresh = true,
            IsPersistent = rememberMe,
            ExpiresUtc = DateTime.UtcNow.AddDays(14),
            IssuedUtc = DateTime.UtcNow
        };

        List<Claim> claims = new List<Claim>();
        claims.Add(new Claim(ClaimTypes.NameIdentifier, appUserState.EmailAddress));
        claims.Add(new Claim(ClaimTypes.Name, appUserState.Name));
        claims.Add(new Claim("userState", appUserState.ToString()));

        ClaimsIdentity identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

        this.AuthenticationManager.SignIn(authenticationProperties, identity);
    }
}

登录过程有效,但持久性无效。大约 30-60 分钟后会话总是结束,尽管IsPersistent设置为true. 当我进入调试器并检查authenticationProperties对象时,我可以看到IsPersistent确实如此。

我在网上读到,这是确定您的应用程序是否应该让您的用户保持登录状态的标志,即使用户没有积极使用该网站。然而,用户的会话总是结束。

我认识到的一件事是AuthenticationProperties该类内部有一个字典对象:

身份验证属性

当我打开字典时,我可以看到有一个标记.persistent为空值的键。我尝试将此值设置为True(以复制.refresh键的行为)-但这根本没有效果。

身份验证属性

我认为上述问题与问题无关,但我认为我应该分享我已经进行的调查。

如何防止用户自动注销?

标签: c#asp.net-mvcauthenticationasp.net-mvc-5owin

解决方案


当您关闭浏览器会话时,持久性 cookie 不会被清除,它们仍然会过期。设置ExpireTimeSpanCookieAuthenticationOptions的东西更长。


推荐阅读