Asp.Net MVC FormsAuthenticationTicket

ace*_*ace 5 asp.net-mvc

我在Logon方法中设置FormsAuthenticationTicket以手动创建身份验证cookie.如何验证该身份验证cookie并将其分配给Current.User对象.它是在Global.asax页面中完成的吗?

登录代码:

    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");
Run Code Online (Sandbox Code Playgroud)

我如何阅读此cookie并验证用户?我的代码到目前为止在global.asax文件中:

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;
        }
Run Code Online (Sandbox Code Playgroud)

Chu*_*way 3

我将此类代码移至基本控制器中。Controller 类中有一个名为“OnAuthorization”的方法可以被重写。

已经有一段时间了,但我相信所有请求(图像、CSS...等)都会通过 Global.asax 中的 OnAuthorization 方法。通过将授权下推到控制器,您只会将请求发送到控制器/操作