Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem creating persistent authentication cookie: ASP.NET MVC

OK, here's my code to create an authentication cookie:

        // get user's role
        List<UserType> roles = rc.rolesRepository.GetUserRoles(rc.userLoginRepository.GetUserID(userName));
        List<string> rolesList = (from r in roles
                                 select r.ToString()).ToList();
        string[] rolesArr = rolesList.ToArray();

        // create encryption cookie
        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                1,
                userName,
                DateTime.Now,
                DateTime.Now.AddDays(90),
                createPersistentCookie,
                String.Join(";",rolesArr) //user's roles 
                );

        // add cookie to response stream
        string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

        System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
        System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
        //FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);

And here's my code in Global.asax to set the user roles into the user identity:

    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCookie == null || authCookie.Value == "")
        {
            return;
        }
        FormsAuthenticationTicket authTicket = null;
        try
        {
            authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            string[] roles = authTicket.UserData.Split(new char[] { ';' });
            if (Context.User != null)
            {
                Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);
            }
        }
        catch
        {
            return;
        }
    }

However, if "createPersistentCookie" is TRUE in the top example, no persistent cookie is created. If I uncomment the last line like so:

        //System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
        FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);

then the persistent cookie is created on my hard drive. BUT then in the Global.asax code, the UserData field in "authTicket" is blank, so I can't set up the roles properly!

So I have to use SetAuthCookie to create a persistent cookie, but then for some reason the UserData field disappears from the persistent cookie.

What is the answer to this??

like image 240
Cynthia Avatar asked Nov 05 '10 20:11

Cynthia


1 Answers

To create a persistent cookie you need to set the Expires property:

if (authTicket.IsPersistent)
{
    authCookie.Expires = authTicket.Expiration;
}
like image 119
Darin Dimitrov Avatar answered Nov 10 '22 14:11

Darin Dimitrov