ASP.NET MVC Authentication with FormsAuthenticationTicket (maybe)
I'm a PHP guy, but in the process of creating a login page in ASP.NET MVC4. I am expecting to keep the user ID, username and roles in the session. So far I am doing the following. If I am correct this saves a cookie with the username.
[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);
}
My interest is to store more information and control checkout times. I was advised and asked to use the class FormAuthenticationTicket
. I replaced FormsAuthentication.SetAuthCookie(user.Username, user.RememberMe);
with
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)
)
);
It looks cool, I haven't tested it but had flexibility. But the problem is how I could get this information.
How can I get this information back and determine if the user is logged in as well as other necessary information stored internally FormsAuthenticationTicket
.
Thanks in advance.
source to share
Like any ticket:
var cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
var ticketInfo = FormsAuthentication.Decrypt(cookie.Value);
Since this is a security ticket, if you don't need to access information from client-side JavaScript, set HttpOnly to true as well. This means that the cookie is only available on the server.
source to share