问题是 AuthorizeAttribute 需要用户和角色字符串的常量。您将需要创建一个类似于此博客文章中的内容的 CustomAuthorizeAttribute 。
因此,假设您有一个存储在 web.config 中的字符串,如下所示:
<add key="authorizedUsers" value="Dave,Chuck,Sally" />
然后你有你的自定义授权属性,就像这样:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public IAuthorizationService _authorizationService { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var user = httpContext.User;
if (!user.Identity.IsAuthenticated)
{
return false;
}
var users = System.Configuration.ConfigurationManager.AppSettings["authorizedUsers"].Split(',');
if users.Contains(user.Identity.Name)
{
return true;
}
return _authorizationService.Authorize(httpContext);
}
}
请注意,我很快就把它放在一起,所以它没有经过测试。您可以轻松地对其进行修改以从数据库中获取用户名或组名,以便它可以是完全动态的。