Csharp/C#教程:授权不使用角色的属性分享


授权不使用角色的属性

我在使用Authorize属性处理角色方面遇到了麻烦。 这就是我装饰我的控制器的方式:

 [Authorize(Roles = "admin")] public ActionResult Index() { ... } 

这就是我记录用户的方式:

 string roles = "admin"; FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( 1, username, DateTime.Now, DateTime.Now.AddMinutes(30), false, roles ); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket)); HttpContext.Current.Response.Cookies.Add(cookie); 

但我的用户仍被拒绝访问。 我哪里错了?

我偶然发现了一个类似的代码示例: MVC最高投票答案- 如何存储/分配经过身份validation的用户的角色 。

AuthorizeAttribute调用存储在HttpContext.User中的IPrincipal实例上的IsInRole方法。 默认情况下,IPrincipal没有角色,在这种情况下,IsInRole将始终返回false。 这就是拒绝访问您的操作的原因。

由于您已将用户的角色存储到FormsAuthenticationTicket的UserData属性中 ,因此您必须自己从auth cookie中提取角色并进入IPrincipal实例。 MVC的最高投票答案- 如何存储/分配经过身份validation的用户的角色提供了可以直接添加到global.asax.cs文件中的代码来执行此操作。 我在下面重复了一遍:

上述就是C#学习教程:授权不使用角色的属性分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 protected void Application_AuthenticateRequest(Object sender, EventArgs e) { HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); string[] roles = authTicket.UserData.Split(','); GenericPrincipal userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), roles); Context.User = userPrincipal; } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/990164.html

(0)
上一篇 2021年12月24日
下一篇 2021年12月24日

精彩推荐