这允许“frankl”访问但阻止管理员。我做错了什么?
[Authorize(Order=1,Roles = "Admin",Users="frankl")]
public class AuthorizeBaseController_Admins_frank : Controller
{
}
这可能很简单,但我没有看到任何结合两者的例子,当我尝试添加它时,“Allowmultiple”属性会产生错误。
谢谢, 克里斯
答案 0 :(得分:1)
角色和用户应该专门使用。如果要组合它们,可以编写自定义授权属性:
public class MyAuthoirizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
var user = httpContext.User;
if (!user.Identity.IsAuthenticated)
{
return false;
}
var usersSplit = SplitString(Users);
var rolesSplit = SplitString(Roles);
return
(usersSplit.Length > 0 && usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) ||
(rolesSplit.Length > 0 && rolesSplit.Any(user.IsInRole));
}
private string[] SplitString(string original)
{
if (string.IsNullOrEmpty(original))
{
return new string[0];
}
return (from piece in original.Split(',')
let trimmed = piece.Trim()
where !string.IsNullOrEmpty(trimmed)
select trimmed).ToArray();
}
}
然后:
[MyAuthorize(Order = 1, Roles = "Admin", Users="frankl")]
public class AuthorizeBaseController_Admins_frank : Controller
{
...
}
答案 1 :(得分:0)
不幸的是,AuthorizeAttribrute
将允许您指定有效用户或有效角色 - 而不是两者。以下是MVC 3源代码的相关代码。
protected virtual bool AuthorizeCore(HttpContextBase httpContext) {
if (httpContext == null) {
throw new ArgumentNullException("httpContext");
}
IPrincipal user = httpContext.User;
if (!user.Identity.IsAuthenticated) {
return false;
}
if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) {
return false;
}
if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)) {
return false;
}
return true;
}
您需要将'frankl'设为管理员,或创建自定义授权attribrute