嘿,我有一些想法,但问题是我做不到这一点。
在MVC中,我们可以使用[Authorize]
来“保护”一些操作/控制器,我们可以进行下一步,并为角色和用户提供一些权限。
[Authorize(Roles="Boss", User="Secretary"]
这是好的,但这是一种坏的,因为在现实生活中,我们不知道谁会有权利这样做。所以我的想法是生成角色和用户的字符串,然后返回授权,以使Microsoft在这方面变得神奇。
[Authoize(Role=RoleString(), User=UserString())]
当然,它不工作,如何让它工作?
发布于 2012-04-04 03:15:48
问题是AuthorizeAttribute希望用户和角色字符串都有一个常量。您需要制作一个与this blog post中的内容类似的CustomAuthorizeAttribute。
假设您有一个存储在web.config中的字符串,如下所示:
<add key="authorizedUsers" value="Dave,Chuck,Sally" />
然后,您的自定义authorize属性如下所示:
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);
}
}
请注意,我很快就把它们组合在一起,所以它没有经过测试。您可以很容易地对其进行修改,以便从数据库中获取用户名或组名,从而使其可以完全动态。
https://stackoverflow.com/questions/9999753
复制相似问题