[英]Role added to HttpContext.current.user but isInRole(rolename) is not working
这是我关于身份验证和授权的代码
public class SessionContext { public void setAuthenticationToken(UserAccount userAccount,bool isPersistant,string name) { string data = new JavaScriptSerializer().Serialize(userAccount.Roles); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,name,DateTime.Now,DateTime.Now.AddYears(1),isPersistant,data); var encryptedCookieData = FormsAuthentication.Encrypt(ticket); HttpCookie httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedCookieData) { HttpOnly=true,Expires=ticket.Expiration }; HttpContext.Current.Response.Cookies.Add(httpCookie); } }
我的 Global.asax 有这个方法:
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(new Char[] { ',' }); GenericPrincipal userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), roles); HttpContext.Current.User = userPrincipal; Debug.WriteLine(roles.FirstOrDefault() +" "+ userPrincipal.IsInRole("Admin")); } }
但是当我使用[Authorize(Roles="Admin")]授权不起作用。
我尝试了这些解决方案,但没有奏效:
注意:如您所见,我在 Global.asax 中添加了 Debug.WriteLine() 以显示 userPrincipal 角色状态,但始终返回 false。
注意:如果可以,请向我展示另一种使用非基于 OWIN 的授权和身份验证的方法
我意识到问题是在将角色名称保存到 HttpContext 时它使用“”保存角色名称,而它必须在没有“”的情况下保存
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.