Rupin L
Rupin L

Reputation: 51

How to retrieve a stored cookie in mvc4?

This is the code I use to store a cookie after user is authenticated.

var authTicket = new FormsAuthenticationTicket(
    1,
    Session["UserID"].ToString(),  //user id
    DateTime.Now,
    DateTime.Now.AddDays(1),  // expiry
    true,  //true to remember
    "", //roles 
    "/"
);

HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
if (authTicket.IsPersistent) { cookie.Expires = authTicket.Expiration; }
Response.Cookies.Add(cookie);

What should I do next to retrieve this cookie when the user visits the site again ?

Upvotes: 0

Views: 456

Answers (1)

John Wu
John Wu

Reputation: 52280

To get the cookie:

HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

To get the ticket inside the cookie:

FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

Typical way of doing it-- implement AuthenticateRequest in global.asax.cs...something like this....

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie != null)
    {
        // Get the forms authentication ticket.
        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        var identity = new GenericIdentity(authTicket.Name, "Forms");
        var principal = new MyPrincipal(identity);

        // Get the custom user data encrypted in the ticket.
        string userData = ((FormsIdentity)(Context.User.Identity)).Ticket.UserData;
        // Deserialize the json data and set it on the custom principal.
        var serializer = new JavaScriptSerializer();
        principal.User = (User)serializer.Deserialize(userData, typeof(User));
        // Set the context user.
        Context.User = principal;
    }
}

...then, whenever any of your code needs to access the current user, just get the context user:

var user = HttpContext.Current.User;

Link

Upvotes: 1

Related Questions