在 ASP .Net MVC 中使用 cookie 时记住我选项不起作用

Remember me option not working using cookies in ASP .Net MVC

我使用 asp .net MVC 创建了登录名,并且为 select "Remember me" 选项的用户添加了一个 cookie。下面是用于添加 cookie

的代码
 if (model.LoginViewModel.RememberMe)
 {
    var authTicket = new FormsAuthenticationTicket(
                        1,
                        model.LoginViewModel.Email,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(20), // expiry
                        model.LoginViewModel.RememberMe, //true to remember
                        "",
                        "/");

    //encrypt the ticket and add it to a cookie
    HttpCookie cookie = new HttpCookie(
                           FormsAuthentication.FormsCookieName,
                           FormsAuthentication.Encrypt(authTicket));
    Response.Cookies.Add(cookie);
 }

我也将此配置添加到 web.config。

<authentication mode="Forms">
  <forms loginUrl="~/candidate" timeout="2880" />
</authentication>

第二次登录时还是看不到登录信息

我是否遗漏了一些东西,或者有其他方法可以做到这一点吗?

使用 OWIN 复制 FormsAuthentication 的最低限度将使用与此类似的东西:

using System.Collections.Generic;
using System.Security.Claims;
using System.Web;
//
using Microsoft.Owin.Security;

namespace YourProjectNamespace
{
    public class ClaimsAuthManager
    {
        public void SignIn(string userName, string displayName = "", bool createPersistantLogin = false)
        {
            var claims = new List<Claim>();

            claims.Add(new Claim(ClaimTypes.Name, userName));
            claims.Add(new Claim(ClaimTypes.IsPersistent, createPersistantLogin.ToString()));

            claims.Add(new Claim(ClaimTypes.GivenName, string.IsNullOrWhiteSpace(displayName) ? userName : displayName));

            var identity = new ClaimsIdentity(claims, AuthenticationTypes.ApplicationCookie);

            GetAuthenticationContext().SignIn(new AuthenticationProperties { IsPersistent = createPersistantLogin }, identity);
        }

        public void SignOut()
        {
            GetAuthenticationContext().SignOut(AuthenticationTypes.ApplicationCookie);
        }

        private IAuthenticationManager GetAuthenticationContext()
        {
            return HttpContext.Current.GetOwinContext().Authentication;
        }
    }
}

与 FormsAuthentication 不同,这不是 static/singleton 对象,因此您需要将其注入控制器,或者在每次要让用户登录或注销时创建一个新实例。像这样:

new ClaimsAuthManager().SignIn(model.LoginViewModel.Email, null, model.LoginViewModel.RememberMe);