记录FormsAuthentication的使用方法
配置,配置mode="Forms",其他属性详见 MSDN(点我直接查看各authentication属性) 。
<configuration>
<system.web>
<authentication mode="Forms">
<forms name="cookiename" loginUrl="/home/login" defaultUrl="/" timeout="" 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(, username, DateTime.Now, DateTime.Now.AddDays(), 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
最新文章
- Windows Store App 全球化:引用类库资源
- linux mutext spinlock 性能分析
- [转]Material Design Library 23.1.0的新变化与代码实战
- C语言每日一题之No.4
- linq数据使用
- mount失败
- Http、Socket的区别
- 有两个指针pa,pb分别指向有两个数,a,b,请写一个函数交换两个指针的指向,也就是让pa指向b,让pb指向a
- windows版的node.js简单示例
- Foxmail 7.0破解版,拷贝到新机器后,发送邮件乱码问题
- PCI设备内存操作函数总结
- Java IO模型
- Android源代码下载 “Gerrit下载源代码”
- Groovy学习笔记-使用多赋值
- Thinkphp table doesn&#39;t exist
- [NOIp2009] $Hankson$ 的趣味题
- 基本类型变量、引用类型变量的在java中的存放位置
- Python学习之旅(三十四)
- python split()函数的用法
- Python RabbitMQ RPC实现