记录FormsAuthentication的使用方法

配置,配置mode="Forms",其他属性详见 MSDN(点我直接查看各authentication属性) 。 

<configuration>
  <system.web>
    <authentication mode="Forms">
      <forms name="cookiename" loginUrl="/home/login" defaultUrl="/" timeout="30" path = "/">
      </forms>
    </authentication>
  </system.web>
</configuration>

登录,有两种方法,二选一即可,两者效果是一致的,后者可以带自定义数据(比如可以放用户角色)。

[AllowAnonymous]
[HttpPost]
public ActionResult Login(string username,string password)
{

    //方法1,方便快捷
    FormsAuthentication.SetAuthCookie(username, false);

    //方法2,可以带自定义数据
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddDays(1), true, "自定义数据","/");
    string hashTicket = FormsAuthentication.Encrypt(ticket);
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
    cookie.HttpOnly = true;
    Response.Cookies.Add(cookie);

    //重定向至原始请求URL上
    string returnUrl = FormsAuthentication.GetRedirectUrl(username, false);
    if (!string.IsNullOrEmpty(returnUrl))
    {
        Response.Redirect(returnUrl);
    }
    return View("Index");
}

登录信息,在Login()方法中的username可以在HttpContext.User.Identity.Name获取,而自定义数据则是存在Cookie中的,想要获取自定义数据则事先需要将cookie里保存的值解密成认证票据, FormsAuthenticationTicket.UserData 属性便是我们想要的自定义数据。

[Authorize]
public ActionResult UserInfo()
{
    string cookieName = FormsAuthentication.FormsCookieName;
    HttpCookie authCookie = HttpContext.Request.Cookies[cookieName];
    FormsAuthenticationTicket authTicket = null;
    try
    { 
        authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    }
    catch (Exception ex)
    {

    }
    ViewData["UserName"] = HttpContext.User.Identity.Name;
    ViewData["UserRole"] = authTicket.UserData;

    return View();
}

退出登录,一句SingOut()即可。

[HttpPost]
public ActionResult Logout()
{
    FormsAuthentication.SignOut();
    return View("Index");
}

一个奇怪的现象,我折腾了一个晚上始终没能成功登录(ASP.NET MVC5),总是在 var cookie =  HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName] 这一步出了问题,总是出现 cookie==null ,而HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName].Value !=null 的现象。最后清了下浏览器缓存......问题消失了.......

FormsAuthentication实现比较简单,无法满足复杂身份认证业务的需求,这里仅作为我个人的学习记录、知识储备目录。

参考引用

基于FormsAuthentication的用户、角色身份认证:https://blog.csdn.net/lenovouser/article/details/53197603

Asp.Net MVC 身份验证-Forms : https://www.cnblogs.com/JoeSnail/p/8250231.html

经典FormsAuthenticationTicket 分析 :https://blog.csdn.net/wdbs_05/article/details/73737725

总结FormsAuthentication的使用 : https://www.cnblogs.com/ShaYeBlog/p/6268206.html

.Net MVC 身份验证 :https://www.cnblogs.com/wwj1992/p/8196131.html

原文地址:https://www.cnblogs.com/xurongjian/p/9588881.html