通用授权属性多个角色 ASP.NET 核心
Generic Authorize Attribute multiple Roles ASP.NET Core
我正在尝试实现一个通用的多重授权属性,该属性了解每个方法都由我指定的角色或名为 "SysAdmin" 的角色授权,该角色将出现在所有方法中,示例:
[Authorize(Roles = "Role_A,SysAdmin")]
public Method1
{
//actions
}
[Authorize(Roles = "Role_B,SysAdmin")]
public Method2
{
//actions
}
[Authorize(Roles = "Role_C,SysAdmin")]
public Method3
{
//actions
}
我认为在所有方法中重复 SysAdmin 不是一个好主意,是否有任何解决方案可以将其传递为通用的?
由于您始终需要检查 SysAdmin 角色,我们可以将其作为常量保存在属性中。
[AuthorizeUser(Role = "Role_A")]
public Method1
{
//actions
}
using System.Linq;
public class AuthorizeUserAttribute : AuthorizeAttribute
{
public string Role{ get; set; }
private readonly string SysAdmin = "SysAdmin";
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
return false;
}
// method to get roles array by user name from db or claims
string roles = GetUserRoles(httpContext.User.Identity.Name.ToString());
var splittedRoles = Role.split(",");
return roles.Any(x => splittedRoles.Any(y => y == x || y == SysAdmin))
}
}
为return未授权用户覆盖以下方法
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
我正在尝试实现一个通用的多重授权属性,该属性了解每个方法都由我指定的角色或名为 "SysAdmin" 的角色授权,该角色将出现在所有方法中,示例:
[Authorize(Roles = "Role_A,SysAdmin")]
public Method1
{
//actions
}
[Authorize(Roles = "Role_B,SysAdmin")]
public Method2
{
//actions
}
[Authorize(Roles = "Role_C,SysAdmin")]
public Method3
{
//actions
}
我认为在所有方法中重复 SysAdmin 不是一个好主意,是否有任何解决方案可以将其传递为通用的?
由于您始终需要检查 SysAdmin 角色,我们可以将其作为常量保存在属性中。
[AuthorizeUser(Role = "Role_A")]
public Method1
{
//actions
}
using System.Linq;
public class AuthorizeUserAttribute : AuthorizeAttribute
{
public string Role{ get; set; }
private readonly string SysAdmin = "SysAdmin";
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
return false;
}
// method to get roles array by user name from db or claims
string roles = GetUserRoles(httpContext.User.Identity.Name.ToString());
var splittedRoles = Role.split(",");
return roles.Any(x => splittedRoles.Any(y => y == x || y == SysAdmin))
}
}
为return未授权用户覆盖以下方法
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)