繁体   English   中英

如何为具有角色和权限的ASP.NET MVC5 Web Api创建自定义授权?

[英]How to create custom Authorization for ASP.NET MVC5 Web Api With Roles and Permitions for them?

我正在尝试在Web API上实现基本角色授权,但是最近我意识到我无法使用它,因为我有一个数据库,其中角色与用户相关(很多),而角色与权限相关(很多)例如Create,Update ...等。因此,我试图为用户权限和角色找到最佳的解决方案,以授权访问我的API中的操作。 另外,我不知道是否有更好的方法是仅在前端部分的控制器中进行授权,而只是生成API密钥来避免第三方程序访问我的Web API。

如果要在应用程序内部维护自己的角色,特权和用户映射,则无法使用默认角色提供程序。 对于这种情况,您需要通过扩展System.Web.Security.RoleProvider来创建自己的角色提供程序,如下所示。

 public class CustomRoleProvider : System.Web.Security.RoleProvider
    {
        List<string> userRoles;

        public CustomRoleProvider()
        {
            //Populate the roles union privilege of logged in user inside userRoles
        }


        public override bool IsUserInRole(string username, string roleName)
        {
            //Mandatory to implement
        }


        public override string[] GetRolesForUser(string username)
        {
            //Mandatory to implement
        }

        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }


        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override void CreateRole(string roleName)
        {

        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {

            return true;
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            throw new NotImplementedException();
        }

        public override string[] GetAllRoles()
        {
            throw new NotImplementedException();
        }

        public override string[] GetUsersInRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override bool RoleExists(string roleName)
        {
            throw new NotImplementedException();
        }
    }

一旦实现了此功能,就需要在配置文件中注册RoleProvider,如下所示。

<roleManager cacheRolesInCookie="false" defaultProvider="CustomRoleProvider" enabled="true">
      <providers>
        <clear/>
        <add name="MyCustomRoleProvier" type="YourLibrary.CustomRoleProvider, YourLibraryName"/>
      </providers>
    </roleManager>
  </system.web>

现在,您可以直接在API或Action中使用Authorization filter属性,例如

 [Authorize(Roles = "Admin")]
 public string GetData()
 {
 }

您也可以查看此答案以获取更多详细信息。 自定义角色提供者

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM