覆盖 ASP.Net Core 中的 AuthorizeAttribute 并响应 Json 状态

Override AuthorizeAttribute in ASP.Net Core and respond Json status

我正在从 ASP.Net 框架转移到 ASP.Net 核心。

在 ASP.Net Framework with Web API 2 项目中,我可以像这样自定义 AuthorizeAttribute :

public class ApiAuthorizeAttribute : AuthorizationFilterAttribute
{
    #region Methods

    /// <summary>
    ///     Override authorization event to do custom authorization.
    /// </summary>
    /// <param name="httpActionContext"></param>
    public override void OnAuthorization(HttpActionContext httpActionContext)
    {
        // Retrieve email and password.
        var accountEmail =
            httpActionContext.Request.Headers.Where(
                    x =>
                        !string.IsNullOrEmpty(x.Key) &&
                        x.Key.Equals("Email"))
                .Select(x => x.Value.FirstOrDefault())
                .FirstOrDefault();

        // Retrieve account password.
        var accountPassword =
            httpActionContext.Request.Headers.Where(
                    x =>
                        !string.IsNullOrEmpty(x.Key) &&
                        x.Key.Equals("Password"))
                .Select(x => x.Value.FirstOrDefault()).FirstOrDefault();

        // Account view model construction.
        var filterAccountViewModel = new FilterAccountViewModel();
        filterAccountViewModel.Email = accountEmail;
        filterAccountViewModel.Password = accountPassword;
        filterAccountViewModel.EmailComparision = TextComparision.Equal;
        filterAccountViewModel.PasswordComparision = TextComparision.Equal;

        // Find the account.
        var account = RepositoryAccount.FindAccount(filterAccountViewModel);

        // Account is not found.
        if (account == null)
        {
            // Treat the account as unthorized.
            httpActionContext.Response = httpActionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);

            return;
        }

        // Role is not defined which means the request is allowed.
        if (_roles == null)
            return;

        // Role is not allowed 
        if (!_roles.Any(x => x == account.Role))
        {
            // Treat the account as unthorized.
            httpActionContext.Response = httpActionContext.Request.CreateResponse(HttpStatusCode.Forbidden);

            return;
        }

        // Store the requester information in action argument.
        httpActionContext.ActionArguments["Account"] = account;
    }

    #endregion

    #region Properties

    /// <summary>
    ///     Repository which provides function to access account database.
    /// </summary>
    public IRepositoryAccount RepositoryAccount { get; set; }

    /// <summary>
    ///     Which role can be allowed to access server.
    /// </summary>
    private readonly byte[] _roles;

    #endregion

    #region Constructor

    /// <summary>
    ///     Initialize instance with default settings.
    /// </summary>
    public ApiAuthorizeAttribute()
    {
    }

    /// <summary>
    ///     Initialize instance with allowed role.
    /// </summary>
    /// <param name="roles"></param>
    public ApiAuthorizeAttribute(byte[] roles)
    {
        _roles = roles;
    }

    #endregion
}

在我自定义的 AuthorizeAttribute 中,我可以检查帐户是否有效和 return HttpStatusCode 以及发送给客户端的消息。

我正在尝试在 ASP.Net Core 中做同样的事情,但没有 OnAuthorization 可供我覆盖。

如何实现与 ASP.Net 框架中相同的功能?

谢谢,

您的处理方式不正确。从来没有真正鼓励为此编写自定义属性或扩展现有属性。 ASP.NET Core 角色仍然是系统的一部分以实现向后兼容性,但现在也不鼓励使用它们。

有一个很棒的 2 部分系列,介绍了一些驱动架构的变化以及发现的这种变化和应该利用的方式 here。如果你仍然想依赖角色,你可以这样做,但我建议使用策略。

要连接策略,请执行以下操作:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthorization(options =>
    {
        options.AddPolicy(nameof(Policy.Account), 
                          policy => policy.Requirements.Add(new AccountRequirement()));
    });

    services.AddSingleton<IAuthorizationHandler, AccountHandler>();
}

为了方便起见,我创建了一个 Policy 枚举。

public enum Policy { Account };

这样装饰入口点:

[
    HttpPost,
    Authorize(Policy = nameof(Policy.Account))
]
public async Task<IActionResult> PostSomething([FromRoute] blah)
{
}

AccountRequirement只是占位符,需要实现IAuthorizationRequirement接口

public class AccountRequirement: IAuthorizationRequirement { }

现在我们只需要创建一个处理程序并将其连接到 DI。

public class AccountHandler : AuthorizationHandler<AccountRequirement>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        AccountRequirement requirement)
    {
        // Your logic here... or anything else you need to do.
        if (context.User.IsInRole("fooBar"))
        {
            // Call 'Succeed' to mark current requirement as passed
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

其他资源

我的评论看起来很糟糕,所以我 post 一个答案,但只有当你使用 MVC 时才有用:

// don't forget this 
services.AddSingleton<IAuthorizationHandler, MyCustomAuthorizationHandler>();
services
   .AddMvc(config => { var policy = new AuthorizationPolicyBuilder() 
      .RequireAuthenticatedUser() .AddRequirements(new[] { new MyCustomRequirement() }) 
       .Build(); config.Filters.Add(new AuthorizeFilter(policy)); }) 

我还注意到 async 关键字对于 "HandleRequirementAsync" 签名来说是多余的,在问题代码中。我想返回 Task.CompletedTask 可能会很好。