我在 ASP.NET MVC 5 中工作,我正在使用 ASP.NET Identity。我在这里按照 LukeP 的解决方案来访问我的ApplicationUser
自定义属性(例如User.DisplayUsername
或User.DOB
)。就像 Luke 建议的那样,我现在有一个自定义的 IPrincipal 实现(基本上与他完全相同的代码)。
然而,这有一个问题,我怀疑这与CustomPrincipal
类上的这行代码有关:
public bool IsInRole(string role) { return false; }
我有一个控制器ReviewController
,在那里我有这个:
[Authorize(Roles = "Admin")]
public class ReviewController : Controller
{
// controller stuff
}
这是行不通的。即使我以管理员身份登录的用户也是如此。所以我尝试通过对IsInRole
方法执行此操作来改进代码:
public class CustomPrincipal : ICustomPrincipal
{
public IIdentity Identity { get; private set; }
public bool IsInRole(string role)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new BBContext()));
return roleManager.Roles.All(r => r.Name == role);
}
public CustomPrincipal(string email)
{
this.Identity = new GenericIdentity(email);
}
public string Id { get; set; }
public string DisplayUsername { get; set; }
public DateTime DOB { get; set; }
}
从我现在服务于ReviewController
. 但是它仍然是错误的,因为即使不是管理员角色的用户也被允许访问。我也知道为什么会这样,但只是不知道如何解决这个问题。
我怎样才能让它正常工作?