ace
ace

Reputation: 215

Asp.Net MVC FormsAuthenticationTicket

Im setting FormsAuthenticationTicket in the Logon method to manually create an authentication cookie. How do I validate that authentication cookie and assign it the Current.User object. Is it done in the Global.asax page?

Logon code:

    FormsAuthenticationTicket Authticket = new
                            FormsAuthenticationTicket(1,
                            model.UserName,
                            DateTime.Now,
                            DateTime.Now.AddYears(1),
                            true,
                            "",
                            FormsAuthentication.FormsCookiePath);

                string hash = FormsAuthentication.Encrypt(Authticket);

                HttpCookie Authcookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);

                if (Authticket.IsPersistent) Authcookie.Expires = Authticket.Expiration;

                Response.Cookies.Add(Authcookie);


                if (!String.IsNullOrEmpty(returnUrl))
                {
                    return Redirect(returnUrl);
                }

                return RedirectToAction("Index", "Home");

How do i read this cookie and validate the user? my code so far in the global.asax file:

HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            FormsIdentity id = new FormsIdentity(authTicket);
            GenericPrincipal principal = new GenericPrincipal(id,null);
            Context.User = principal;
        }

Upvotes: 5

Views: 3613

Answers (1)

Chuck Conway
Chuck Conway

Reputation: 16435

I moved this type of code into a base controller. There is a method called "OnAuthorization" in the Controller class that can be overridden.

It's been a little while, but I believe all requests (images, css... etc) where going through the OnAuthorization method in the Global.asax. By pushing the authorization down to the controller you are only getting the request to your controller/actions

Upvotes: 3

Related Questions