限制对MVC操作的访问

时间:2012-06-18 21:18:43

标签: c# asp.net-mvc

我有一个ASP.NET MVC网站,我已经建立了一个权限系统。例如,当前用户没有足够的权限时,会隐藏一些链接。但是,如果他们手动输入该链接的URL,他们仍然可以访问该内容。

我知道我可以使用[Authorize]属性来阻止没有合适用户角色的用户,但是如何实现我自己的属性来阻止不符合自定义要求的用户的操作,而无需编写在每个行动中手动检查?

2 个答案:

答案 0 :(得分:9)

您可以编写自定义Authorize属性并覆盖AuthorizeCore方法,您可以在其中放置自定义授权逻辑:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authroized = base.AuthorizeCore(httpContext);
        if (!authroized)
        {
            return false;
        }

        // at this stage the base authorization process has passed.
        // now implement your custom authorization logic and return true or false

        // here you have access to the HttpContext and as a consequence to all
        // request and route parameters so you could implement any 
        // authorization logic you want

        // And of course if you want a completely custom authorization logic 
        // ignoring the base functionality don't call the base method above
        // but completely override anything here
    }
}

现在剩下的就是用这个自定义属性装饰相应的控制器/动作。

答案 1 :(得分:1)

如果您使用的是ASP.NET成员资格,则可以配置RoleProvider并为用户提供角色。

然后,您可以使用AuthorizeAttribute上的Roles属性来检查角色。

[Authorize(Roles="Admin, SuperUser")]
相关问题