asp.net-mvc - Asp.Net MVC FormsAuthenticationTicket

标签 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");

我如何读取此 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;
        }

最佳答案

我将这种类型的代码移到了基本 Controller 中。 Controller 类中有一个名为“OnAuthorization”的方法可以被覆盖。

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

关于asp.net-mvc - Asp.Net MVC FormsAuthenticationTicket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3260766/

相关文章:

c# - 如何找出我的 ASP.Net MVC 应用程序以哪个用户身份运行?

使用 RouteBase 的 C# MVC 路由

c# - 具有必需类和多个可选类的 View 模型

asp.net-mvc - AutoMapper 奇怪的 IQueryable 投影异常

c# - 从 Controller 访问它时,我的 MvcApplication 的属性为 null

jquery - ASP.NET MVC ModelBinder 无法处理 GET 请求和/或 jQuery AJAX?

ASP.NET MVC - 我需要呈现部分的操作方法。我该怎么做?

c# - 在 MVC "Specified cast is not valid"中填充我的模型时出错

c# - 如何将文档从 Sharepoint 文档库返回给用户?

asp.net-mvc - 将 SPA 分割为多个组件并使用 AngularJS