现在我像这样装饰一个方法,以允许“成员”访问我的控制器动作
[Authorize(Roles="members")]
如何允许多个角色?例如,下面的不工作,但它显示了我正在尝试做什么(允许“成员”和“管理员”访问):
[Authorize(Roles="members", "admin")]
现在我像这样装饰一个方法,以允许“成员”访问我的控制器动作
[Authorize(Roles="members")]
如何允许多个角色?例如,下面的不工作,但它显示了我正在尝试做什么(允许“成员”和“管理员”访问):
[Authorize(Roles="members", "admin")]
当前回答
对于MVC4,使用枚举(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;
}
}
}
这是修改的FNHMVC的一部分由fabicio Martínez Tamayo https://github.com/fabriciomrtnz/FNHMVC/
其他回答
另一个清晰的解决方案是使用常量来保持约定,并添加多个[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
我把答案混在一起,提出了这个方法。
首先,我们为角色访问创建一个枚举。
public enum ERoleAccess
{
[Description("Admin User")]
Admin = 1,
[Description("General User")]
User = 2,
[Description("Editor User")]
Editor = 3,
}
其次,我们需要一个用于客户MVC授权的属性过滤器。
public class RolesAttribute:AuthorizeAttribute
{
public RolesAttribute(params ERoleAccess[] roles)
{
Roles = string.Join(",", roles);
}
}
最后,我们可以在控制器或动作上使用“RolesAttribute”。
[Roles(ERoleAccess.Admin, ERoleAccess.Editor, ERoleAccess.User)]
在这种方法中,我们使用可选字符串值的数量。 (1=管理员,2=用户,…)
它有助于减小令牌大小和比较性能。
对于MVC4,使用枚举(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;
}
}
}
这是修改的FNHMVC的一部分由fabicio Martínez Tamayo https://github.com/fabriciomrtnz/FNHMVC/
一个可能的简化是子类AuthorizeAttribute:
public class RolesAttribute : AuthorizeAttribute
{
public RolesAttribute(params string[] roles)
{
Roles = String.Join(",", roles);
}
}
用法:
[Roles("members", "admin")]
从语义上看,它和Jim Schmehil的答案是一样的。
添加子类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();
}