Ziy*_*een 3 asp.net authentication asp.net-mvc asp.net-mvc-4
我是一个PHP人,但我正在ASP.NET MVC4中创建一个登录页面.我希望在会话中存储用户的ID,用户名和角色.到目前为止,我正在做的事情如下.如果我是正确的,它会使用用户名保存cookie.
[HttpPost]
public ActionResult Login(Models.UserLoginModel user)
{
if (ModelState.IsValid)
{
Models.User u = new Models.User();
if (u.IsValid(user.Username, user.Password))
{
FormsAuthentication.SetAuthCookie(user.Username, user.RememberMe);
return RedirectToAction("Index", "Accounts");
}
else
{
ModelState.AddModelError("", "Login data is incorrect!");
}
}
return View(user);
}
Run Code Online (Sandbox Code Playgroud)
我的兴趣是存储更多信息并控制验证时间.我被告知并要求 FormAuthenticationTicket
上课.我替换FormsAuthentication.SetAuthCookie(user.Username, user.RememberMe);
了
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
(
1,
user.Username,
DateTime.Now,
DateTime.Now.AddMinutes(30),
false,
"Some User Data",
FormsAuthentication.FormsCookiePath
);
Response.Cookies.Add
(
new HttpCookie
(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(ticket)
)
);
Run Code Online (Sandbox Code Playgroud)
它看起来很酷,但我没有测试它,具有灵活性.但问题是我如何能够收到这些信息.
如何获取这些信息并确定用户是否已登录以及保存在其中的其他必要信息FormsAuthenticationTicket
.
提前致谢.
就像你会买票一样:
var cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
var ticketInfo = FormsAuthentication.Decrypt(cookie.Value);
Run Code Online (Sandbox Code Playgroud)
由于它是安全票证,如果您不需要从客户端JavaScript访问信息,也可以将HttpOnly设置为true.这意味着cookie只能在服务器上访问.
归档时间: |
|
查看次数: |
9362 次 |
最近记录: |