Reputation: 3300
I am a PHP guy but am in the process of making a log-in page in ASP.NET MVC4. I am expecting to store the ID, Username and Roles of the user in session. So far what I am doing is as follows. If I am correct it saves the 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 validation time. I was advised and asked to use FormAuthenticationTicket
class. 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 didn't test it though, has flexibility. But problem is how I could receive this information.
How can I get these information back and determine if the user is logged in and also other necessary information saved inside the FormsAuthenticationTicket
.
Thanks in advance.
Upvotes: 4
Views: 10553
Reputation: 50728
Like you would any ticket:
var cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
var ticketInfo = FormsAuthentication.Decrypt(cookie.Value);
Since it's a security ticket, if you don't need to access the information from client JavaScript, also set HttpOnly to true. This means the cookie is only accessible on the server.
Upvotes: 6