【发布时间】:2011-03-15 16:19:08
【问题描述】:
我在 SO 描述 how to set up custom user roles 上找到了一个很好的答案,我在我的项目中也做了同样的事情。所以在我的登录服务中,我有:
public ActionResult Login() {
// password authentication stuff omitted here
var roles = GetRoles(user.Type); // returns a string e.g. "admin,user"
var authTicket = new FormsAuthenticationTicket(
1,
userName,
DateTime.Now,
DateTime.Now.AddMinutes(20), // expiry
false,
roles,
"/");
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);
return new XmlResult(xmlDoc); // don't worry so much about this - returns XML as ActionResult
}
在 Global.asax.cs 中,我有(从另一个答案逐字复制):
protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
var authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null) {
var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var roles = authTicket.UserData.Split(new Char[] { ',' });
var userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), roles);
Context.User = userPrincipal;
}
}
然后,在我的ServicesController 课程中,我有:
[Authorize(Roles = "admin")]
//[Authorize]
public ActionResult DoAdminStuff() {
...
}
我以具有“管理员”角色的用户身份登录,这很有效。然后我调用 /services/doadminstuff - 我被拒绝访问,即使当我在 Global.asax.cs 中放置一个断点时,我可以看到我的角色确实包括“管理员”。如果我注释掉第一个 Authorize 属性(带有角色)并只使用普通的 Authorize,那么我可以访问该服务。
我一定遗漏了一些重要的东西——但是从哪里开始寻找呢?
【问题讨论】:
标签: asp.net asp.net-mvc