允许多个角色访问控制器操作

By simon at 2018-02-07 • 0人收藏 • 52人看过

现在我装饰一个这样的方法,让“成员”访问我的 控制器行动

[Authorize(Roles="members")]
我如何允许超过一个角色?例如以下不起作用 但它显示了我正在尝试做什么(允许“成员”和“管理员”访问):
[Authorize(Roles="members", "admin")] 

6 个回复 | 最后更新于 2018-02-07
2018-02-07   #1

另一个选择是使用一个单一的授权过滤器,但你删除 内部的报价。

[Authorize(Roles="members, admin")]

2018-02-07   #2

如果你想使用自定义角色,你可以这样做: CustomRoles职业:

public static class CustomRoles
{
    public const string Administrator = "Administrador";
    public const string User = "Usuario";
}
用法
[Authorize(Roles = CustomRoles.Administrator +","+ CustomRoles.User)]
如果你有几个角色,也许是你可以结合他们(为清晰)像这样:
public static class CustomRoles
{
     public const string Administrator = "Administrador";
     public const string User = "Usuario";
     public const string AdministratorOrUser = Administrator + "," + User;  
}
用法
[Authorize(Roles = CustomRoles.AdministratorOrUser)]

2018-02-07   #3

对于MVC4,使用Enum(UserRoles)和我的角色,我使用自定义 AuthorizeAttribute。 在我的控制行动,我做:

[CustomAuthorize(UserRoles.Admin, UserRoles.User)]
public ActionResult ChangePassword()
{
    return View();
}
我使用这样的自定义AuthorizeAttribute:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class CustomAuthorize : AuthorizeAttribute
{
    private string[] UserProfilesRequired { get; set; }

    public CustomAuthorize(params object[] userProfilesRequired)
    {
        if (userProfilesRequired.Any(p => p.GetType().BaseType != typeof(Enum)))
            throw new ArgumentException("userProfilesRequired");

        this.UserProfilesRequired = userProfilesRequired.Select(p => Enum.GetName(p.GetType(), p)).ToArray();
    }

    public override void OnAuthorization(AuthorizationContext context)
    {
        bool authorized = false;

        foreach (var role in this.UserProfilesRequired)
            if (HttpContext.Current.User.IsInRole(role))
            {
                authorized = true;
                break;
            }

        if (!authorized)
        {
            var url = new UrlHelper(context.RequestContext);
            var logonUrl = url.Action("Http", "Error", new { Id = 401, Area = "" });
            context.Result = new RedirectResult(logonUrl);

            return;
        }
    }
}
这是由FabricioMartínezTamayo修改的FNHMVC的一部分

2018-02-07   #4

一个可能的简化将是子类AuthorizeAttribute:

public class RolesAttribute : AuthorizeAttribute
{
    public RolesAttribute(params string[] roles)
    {
        Roles = String.Join(",", roles);
    }
}
用法:
[Roles("members", "admin")]
在语义上它和Ji是一样的米Schmehil的答案。

2018-02-07   #5

更好的代码添加一个子类AuthorizeRole.cs

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    class AuthorizeRoleAttribute : AuthorizeAttribute
    {
        public AuthorizeRoleAttribute(params Rolenames[] roles)
        {
            this.Roles = string.Join(",", roles.Select(r => Enum.GetName(r.GetType(), r)));
        }
        protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAuthenticated)
            {
                filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary {
                  { "action", "Unauthorized" },
                  { "controller", "Home" },
                  { "area", "" }
                  }
              );
                //base.HandleUnauthorizedRequest(filterContext);
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary {
                  { "action", "Login" },
                  { "controller", "Account" },
                  { "area", "" },
                  { "returnUrl", HttpContext.Current.Request.Url }
                  }
              );
            }
        }
    }
如何使用这个
[AuthorizeRole(Rolenames.Admin,Rolenames.Member)]

public ActionResult Index()
{
return View();
}

2018-02-07   #6

另一个明确的解决方案,你可以使用常量来保持约定和添加 多个[Authorize]属性。看一下这个:

public static class RolesConvention
{
    public const string Administrator = "Administrator";
    public const string Guest = "Guest";
}
然后在控制器中:
[Authorize(Roles = RolesConvention.Administrator )]
[Authorize(Roles = RolesConvention.Guest)]
[Produces("application/json")]
[Route("api/[controller]")]
public class MyController : Controller

登录后方可回帖

Loading...