首页 > 解决方案 > 记住我选项在 ASP .Net MVC 中不使用 cookie

问题描述

我使用 asp .net MVC 创建了登录,并为选择“记住我”选项的用户添加了一个 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>

当我第二次登录时,我仍然看不到我的登录详细信息。

我在这里错过了什么还是有其他方法可以做到这一点?

标签: asp.net-mvcauthenticationcookiesremember-me

解决方案


使用 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 不同,这不是静态/单例对象,因此您需要将其注入到控制器中,或者在每次要让用户登录或注销时创建一个新实例。像这样的东西:

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

推荐阅读