【问题标题】:how to relate roles in filter attribute with my database?如何将过滤器属性中的角色与我的数据库相关联?
【发布时间】:2013-02-02 00:48:03
【问题描述】:

Asp.net MVC 使用什么数据源来查看用户是否属于哪个角色。以及如何更改它以使其与我自己的数据库表一起使用(当我写 [Autorize(Roles="admin")] 时,如果用户在角色中,它会检查表)

【问题讨论】:

    标签: asp.net-mvc roles


    【解决方案1】:

    Asp.net MVC 使用什么数据源来查看用户是否属于哪个角色。

    它使用在您的 web.config 中配置的RoleProvider。如果您想使用自定义表,您可以通过继承 RoleProvider 类并实现抽象成员来编写 custom role provider。 IsUserInRole 方法是您应该始终实现的方法,因为在这种情况下将使用该方法:

    public class MyRoleProvider: RoleProvider
    {
        public override bool IsUserInRole(string username, string roleName)
        {
            // go and hit your custom datasource to verify if the user 
            // is in the required role and return true or false from this
            // method
            ...
        }
    }
    

    然后您可以在 web.config 中注册您的自定义角色提供者以替换默认角色提供者:

    <system.web>
        ...
        <roleManager enabled="true" defaultProvider="MyRoleProvider"> 
            <providers> 
                <add name="MyRoleProvider" type="Mynamespace.MyRoleProvider" /> 
            </providers> 
        </roleManager>
    </system.web>
    

    如果您不想使用任何提供程序(从您的previous question 来看似乎是这种情况),那么您应该编写一个自定义的Authorize 属性,该属性根本不使用角色提供程序,而是使用您的一些自定义代码:

    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (!httpContext.User.Identity.IsAuthenticated)
            {
                // no user is authenticated => no need to go any further
                return false;
            }
    
            // at this stage we have an authenticated user
            string username = httpContext.User.Identity.Name;
            return IsInRole(username, this.Roles);
        }
    
        private bool static IsInRole(string username, string roles)
        {
            // the username parameter will contain the currently authenticated user
            // the roles parameter will contain the string specified in the attribute
            // (for example "admin")
            // so here go and hit your custom tables and verify if the user is
            // in the required role
            ... 
        }
    }
    

    最后用这个自定义属性来装饰你的控制器动作,而不是依赖基于角色提供者的默认属性:

    [MyAutorize(Roles = "admin")]
    public ActionResult Index()
    {
        ...
    }
    

    【讨论】:

    • 很棒的帖子,非常感谢,这很有帮助,我有 2 周的时间寻找这个,我已经下载了 3 本关于 asp.net mvc 4 的电子书,但我还没有找到这个,你能告诉我你什么时候学过这个(电子书的书名)
    • 嗯,你花了 2 周时间,而我花了 10 年时间在 ASP.NET 平台上的业务线应用程序上工作。我就是这么学的。
    • 函数是gerolesforuser()而不是IsUserInRole,我认为你需要10年以上:)
    • 谢谢@DarinDimitrov。这是我过去两周以来一直在寻找的东西。终于解决了我的问题。但是,我想在操作方法上授权多个角色,如下所示。 [MyAutorize(Roles = "admin | member")] public ActionResult Index() { ... } 我应该如何使用授权属性?
    • @ajexpress,你总是可以用一些分隔符分割字符串,然后为每个角色授权。
    猜你喜欢
    • 2016-10-31
    • 1970-01-01
    • 2013-11-02
    • 2016-04-25
    • 2020-05-21
    • 1970-01-01
    • 2017-12-07
    • 2020-01-25
    • 1970-01-01
    相关资源
    最近更新 更多