加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 在MVC2中使用FormsAuthenticationTicket cookie

发布时间:2020-12-16 03:19:58 所属栏目:asp.Net 来源:网络整理
导读:我目前正在尝试在ASP.NET MVC2 Web应用程序中实现一些自定义安全性. 我正在尝试做一些非常简单的事情,因为我的代码如下所示,但出于某种原因,如果我在我的一个控制器操作上使用[Authorize(Roles =“Admins”)]属性,请检查Context.User.IsInRole(“Admins”) )
我目前正在尝试在ASP.NET MVC2 Web应用程序中实现一些自定义安全性.

我正在尝试做一些非常简单的事情,因为我的代码如下所示,但出于某种原因,如果我在我的一个控制器操作上使用[Authorize(Roles =“Admins”)]属性,请检查Context.User.IsInRole(“Admins”) )或Page.User.IsInRole(“Admins”)它总是假的.

User.Identity.Name也是空白也很奇怪.

请参阅下面的代码,我在cookie中使用FormsAuthenticationTicket,然后在Gloabl.asax中的Application_AuthenticateRequest事件句柄中使用它来设置Context.User和GenericPrincipal对象.

我的登录代码:

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(string username,string password)
        {  

            //this would obviously do a check against the supplied username and password
            if (true)
            {
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,username,DateTime.Now,DateTime.Now.AddMinutes(15),false,"Admins|Users|Members");

                string encTicket = FormsAuthentication.Encrypt(ticket);

                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,encTicket);

                this.Response.Cookies.Add(cookie);
                string url = FormsAuthentication.GetRedirectUrl(username,false);

                Response.Redirect(url);               
            }


            return View();

        }

我的Global.asax代码:

void MvcApplication_AuthenticateRequest(object sender,EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;

            var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (cookie != null)
            {                  

                // Get the authentication ticket 
                // and rebuild the principal & identity
                FormsAuthenticationTicket authTicket =
                  FormsAuthentication.Decrypt(cookie.Value);
                string[] roles = authTicket.UserData.Split(new Char[] { '|' });
                GenericIdentity userIdentity = new GenericIdentity(authTicket.Name);
                GenericPrincipal userPrincipal =
                    new GenericPrincipal(userIdentity,roles);

                context.User = userPrincipal;

            }

一旦我设置了context.User,我可以在监视窗口中查看对象设置完美,使用正确的名称等正确的角色,但是如果我尝试锁定控制器操作或从我的站点中的任何位置使用Principal它始终设置为空字符串,不分配任何角色!

我猜我在做一些非常愚蠢的事情,但如果有人能指出这一点,我会非常感激.

解决方法

检查您是否将新的userPrincipal分配给global.asax中的OnPostAuthenticate请求中的HttpContext和当前线程:

HttpContext.Current.User = userPrincipal;
Thread.CurrentPrincipal = userPrincipal;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读