ASP.NET MVC3:自定义[授权]属性 [英] ASP.NET MVC3: custom [authorise] attribute

查看:80
本文介绍了ASP.NET MVC3:自定义[授权]属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据库中,系统用户具有他/她可以访问的模块的列表

我想可以添加哪些检查,这是一个情况下授权属性。

例如。 [授权(用户ID,ControllerName)]

都到一些code,确保与用户ID指定的用户,在他/她的名单有控制器名称。

目前,你可以简单地绕过事实的标签是不可见的,通过使用URL。 (我有code这已经检查,如果用户已经指定接入和隐藏/显示选项卡)


解决方案

 公共类MyAuthorizeAttribute:AuthorizeAttribute
{
    保护覆盖布尔AuthorizeCore(HttpContextBase的HttpContext)
    {
        VAR isAuthorized = base.AuthorizeCore(HttpContext的);
        如果(!isAuthorized)
        {
            返回false;
        }        字符串的currentUser = httpContext.User.Identity.Name;
        字符串currentController = httpContext.Request.RequestContext.RouteData.GetRequiredString(控制器);        // TODO:去砸你的数据库,看看是否可以的currentUser访问
        // currentController并从这里返回真/假        ...
    }
}

再装点您的控制器或动作:

  [MyAuthorize]
公共类FooController的:控制器
{
    ...
}


这是说我怀疑你可能在你的数据库设计,通过存储这些用户访问访问的控制器操作列表去了错误的方式。也许你应该为使用的角色。让数据库了解控制器,只是感觉错了。

所以:

  [授权(角色=美孚,酒吧)]
公共类FooController的:控制器
{
    ...
}

只有具有用户酒吧角色可以访问 FooController的

In my database, the system user has a list of modules he/she can access.

I would like to be able to add an authorise attribute which checks that this is the case.

E.g. [authorise(UserID, ControllerName)]

Which goes to some code, ensures that the User with UserID specified, has the controller name in his/her list.

At the moment you can simply bypass the fact the tabs aren't visible, by using the URL. (I have code which already checks if the user has specified access and hides/shows tabs)

解决方案

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

        string currentUser = httpContext.User.Identity.Name;
        string currentController = httpContext.Request.RequestContext.RouteData.GetRequiredString("controller");

        // TODO: go hit your database and see if currentUser can access
        // currentController and return true/false from here

        ...
    }
}

then decorate your controllers or actions:

[MyAuthorize]
public class FooController: Controller
{
    ...
}


This being said I suspect that you might have gone the wrong way in your database design by storing a list of which user has access to access which controller action. Probably you should have used roles for that. Having the database know about controllers just feels wrong.

So:

[Authorize(Roles = "Foo,Bar")]
public class FooController: Controller
{
    ...
}

Only users that have the Foo or Bar role can access the FooController.

这篇关于ASP.NET MVC3:自定义[授权]属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆