0

嘿,我有一些想法,但问题是我无法完成这项工作。

在 MVC 中,我们可以[Authorize]用来“保护”一些动作/控制器,我们可以进行下一步并为角色和用户提供一些权限。

[Authorize(Roles="Boss", User="Secretary"]

这工作很好,但有点糟糕,因为在现实生活中我们不知道谁将拥有此权利。所以想法是制作角色和用户字符串并返回授权让微软在这方面发挥作用。

[Authoize(Role=RoleString(), User=UserString())]

当然,它不起作用,如何使它起作用?

4

1 回答 1

0

问题是 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);
    }
}

请注意,我很快就把它放在一起,所以它没有经过测试。您可以轻松地对其进行修改以从数据库中获取用户名或组名,以便它可以是完全动态的。

于 2012-04-03T19:15:47.913 回答