在 .net core 5.0 中创建拒绝角色属性

Create a deny role attribute in .netcore 5.0

我想创建一个基于授权属性的属性,而不是授予角色访问 IActionResult 的权限,而是拒绝访问。

我想用 [Deny(Role="role")] 之类的东西装饰 ActionResult,这样如果角色试图访问它,它就会被重定向回引用 url。

我尝试修改了下面的代码,但是很多使用的方法在.netcore 5.0中不存在:

public class DenyAttribute : AuthorizeAttribute 
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        return !base.AuthorizeCore(httpContext);
    }
}

public class DenyByControllerActionAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var controller = httpContext.Request.RequestContext.RouteData.GetRequiredString("controller");
        var action = httpContext.Request.RequestContext.RouteData.GetRequiredString("action");
        var denyRole = string.Format("Deny{0}:{1}", controller, action);
        return !httpContext.User.IsInRole(denyRole) && base.AuthorizeCore(httpContext);
    }
}

由于 .net 5.0 中不再存在 AuthorizeCore 覆盖,如何在 .netcore 5.0 中创建类似上述代码示例的内容?

在 ASP.NET Core 中,您需要实现 AttributeIAuthorizationFilter 来自定义授权属性:

public class DenyAttribute : Attribute, IAuthorizationFilter
{
    public string? Roles { get; set; }
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var originalUrl = context.HttpContext.Request.Headers["Referer"].ToString();
        var userInRole = context.HttpContext.User.IsInRole(Roles);
        if(userInRole)
        {
            context.Result = new RedirectResult(originalUrl);
        }
    }
}

控制器:

[Deny(Roles = "yourRole")]
public IActionResult Test()
{
    return View();
}