【问题标题】:ASP.NET Identity Dynamic Role AuthorizationASP.NET 身份动态角色授权
【发布时间】:2015-12-24 15:08:57
【问题描述】:

由于我是 ASP.NET Identity 的新手,所以当 Jeremy Foster 在演示如何将以下内容变为动态时提出一个问题时,我正在观看有关 MVA 的视频:

[Authorize("Administrators, Users")]
public ActionResult SomeAction()
{
  //Access to only admins and users
}

作为回答,Adam Tuliper 说可以以某种方式使用 Claims 来完成,但我在 Internet 上找不到任何具体的东西,或者我可能不理解。但如果有人能告诉我如何做到这一点,我将不胜感激。

这很重要,因为稍后,我可能希望允许另一个角色访问SomeAction,如果我每次都需要为此重新编译和部署我的应用程序,那就不好了。此外,我可能会将控制权授予用户以更改其他类型用户的访问权限。

过去我通过覆盖Authorize 属性来完成此操作,我从cookie 中提取用户的RoleId 并从数据库中检查用户是否有权访问所请求的操作。但不确定如何使用 Claims 来完成。

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-identity asp.net-identity-2


    【解决方案1】:

    这样的事情怎么样: 您可以将它与数据库一起使用,或者只是在 web.config 中维护授权角色列表。

     [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
        public class MyCustomAuthorizationAttribute : AuthorizeAttribute
        {
            protected override bool AuthorizeCore(HttpContextBase httpContext)
            {
                // Do some logic here to pull authorised roles from backing store (AppSettings, MSSQL, MySQL, MongoDB etc)
                ...
                // Check that the user belongs to one or more of these roles 
                bool isUserAuthorized = ....;
    
                if(isUserAuthorized) 
                    return true;
    
                return base.AuthorizeCore(httpContext);
            }
        }
    

    【讨论】:

    • 这就是我说的我以前做过的。但似乎不是使用像 Identity 这样的基于声明的系统的方式。
    猜你喜欢
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 2010-11-25
    相关资源
    最近更新 更多