繁体   English   中英

ASP.NET身份动态角色授权

[英]ASP.NET Identity Dynamic Role Authorization

当我不熟悉ASP.NET Identity时,我正在观看有关MVA的视频,当杰里米·福斯特(Jeremy Foster)演示时提出了一个问题,即如何使以下内容动态化:

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

对此,亚当·蒂珀勒(Adam Tuliper)表示,可以通过某种方式使用Claims来完成,但是我在Internet上找不到任何具体的东西,或者我可能不太理解。 但是,如果有人可以向我展示如何做到这一点,我将不胜感激。

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

过去,我通过重写Authorize属性来做到这一点,在该属性中,我从cookie中提取用户的RoleId并从数据库中检查用户是否有权访问所请求的操作。 但不确定如何使用Claims来完成。

诸如此类的事情是什么:您可以将其与数据库一起使用,或者仅在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);
        }
    }

暂无
暂无

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

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