开发者

Asp.Net MVC FormsAuthenticationTicket

开发者 https://www.devze.com 2023-01-07 18:46 出处:网络
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 th

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.No开发者_Go百科w.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;
        }


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

0

精彩评论

暂无评论...
验证码 换一张
取 消