Asp.Net MVC FormsAuthenticationTicket

Set Im FormsAuthenticationTicket in the login method to manually create an authentication cookie. How to check this authentication cookie and assign it a Current.User object. Is this done on the Global.asax page?

Login 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 can I read this cookie and verify the user? my code is still in 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;
        }
+5
source share
1 answer

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

, , (, css... ..) OnAuthorization Global.asax. /.

+3

All Articles