在 netcore api 3.1 中读取 AuthorizationFilterContext [英] Reading the AuthorizationFilterContext in netcore api 3.1

查看:77
本文介绍了在 netcore api 3.1 中读取 AuthorizationFilterContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在运行的 netcore 2.2 项目,我在其中实施了一个检查 API 密钥的自定义策略.

I have a working netcore 2.2 project where I have implemented a custom policy that checks for API Keys.

在startup.cs中,我添加了这样的策略

In the startup.cs I am adding this policy like this

//Add Key Policy
services.AddAuthorization(options =>
{
    options.AddPolicy("AppKey", policy => policy.Requirements.Add(new AppKeyRequirement()));
});

在我的 AppKeyRequirement 中,我从 AuthorizationHandler 继承并像这样解析传入请求中的密钥

In my AppKeyRequirement I inherit from AuthorizationHandler and resolve the keys in the incoming requests like this

protected override Task HandleRequirementAsync(AuthorizationHandlerContext authContext, AppKeyRequirement requirement)
{
    var authorizationFilterContext = (AuthorizationFilterContext)authContext.Resource;
    var query = authorizationFilterContext.HttpContext.Request.Query;

    if (query.ContainsKey("key") && query.ContainsKey("app"))
    { // Do stuff

这在 netcore 3.1 中不起作用

This does not work in netcore 3.1

我收到以下错误:

无法将Microsoft.AspNetCore.Routing.RouteEndpoint"类型的对象转换为Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext".

Unable to cast object of type 'Microsoft.AspNetCore.Routing.RouteEndpoint' to type 'Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext'.

在核心 3 及以上版本中执行此操作的正确方法是什么?

What is the correct way to do this in core 3 and above ?

正如 Kirk Larkin 所指出的,.net 3.0 及更高版本中的正确方法是将 IHttpContextAccessor 注入到 Auth 处理程序中并使用它.

As pointed out by Kirk Larkin, the correct way in .net 3.0 and above is to inject IHttpContextAccessor into the Auth handler and use that.

此时我的问题是如何注入它?我无法在 startup.cs 中传递它,或者至少我不知道如何传递.

My question at this point is how do I inject this ? I cant pass this in startup.cs or at least I am not seeing how.

任何想法/提示将不胜感激.

Any ideas/hints will be much appreciated.

推荐答案

ASP.NET Core 5.x

基于 ASP.NET Core 5.0-preview7 以后的公告Resource 属性设置为请求的当前 HttpContext(使用端点路由时).这意味着以下示例将适用于 ASP.NET Core 5.0 以后,无需 IHttpContextAccessor:

ASP.NET Core 5.x

Based on the announcement for ASP.NET Core 5.0-preview7 onwards, the Resource property is set to the current HttpContext for the request (when using endpoint routing). This means the following example will work for ASP.NET Core 5.0 onwards, without the need for IHttpContextAccessor:

public class AppKeyAuthorizationHandler : AuthorizationHandler<AppKeyRequirement>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext authContext, AppKeyRequirement requirement)
    {
        var httpContext = authContext.Resource as HttpContext;
        var query = httpContext.Request.Query;

        if (query.ContainsKey("key") && query.ContainsKey("app"))
        {
            // ...
        }
    }
}

RouteEndpoint 仍然可用,使用 httpContext.GetEndpoint().

在 ASP.NET Core 3.0 之前的版本中,在 MVC 管道期间调用了 IAuthorizationHandler 的实现.在使用端点路由(默认情况下)的 3.0 之后,这些实现由授权中间件 (UseAuthorization()) 调用.这个中间件在 MVC 管道之前运行,而不是作为它的一部分.

In versions prior to ASP.NET Core 3.0, implementations of IAuthorizationHandler were called during the MVC pipeline. In 3.0 onwards, which uses endpoint-routing (by default), these implementations are called by the authorization middleware (UseAuthorization()). This middleware runs before the MVC pipeline, rather than as part of it.

此更改意味着 AuthorizationFilterContext 不再传递给授权处理程序.相反,它是 RouteEndpoint 的一个实例,它不提供对 HttpContext 的访问.

This change means that AuthorizationFilterContext is no longer passed in to authorization handlers. Instead, it's an instance of RouteEndpoint, which doesn't provide access to the HttpContext.

在您的示例中,您仅使用 AuthorizationFilterContext 来获取 HttpContext.在 3.0+ 中,将 IHttpContextAccessor 注入您的授权处理程序并使用它.以下是完整性示例:

In your example, you're only using AuthorizationFilterContext to get hold of HttpContext. In 3.0+, inject IHttpContextAccessor into your authorization handler and use that. Here's an example for completeness:

public class AppKeyAuthorizationHandler : AuthorizationHandler<AppKeyRequirement>
{
    private readonly IHttpContextAccessor httpContextAccessor;

    public AppKeyAuthorizationHandler(IHttpContextAccessor httpContextAccessor)
    {
        this.httpContextAccessor = httpContextAccessor;
    }

    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext authContext, AppKeyRequirement requirement)
    {
        var httpContext = httpContextAccessor.HttpContext;
        var query = httpContext.Request.Query;

        if (query.ContainsKey("key") && query.ContainsKey("app"))
        {
            // ...
        }
    }
}

您可能还需要在 ConfigureServices 中注册 IHttpContextAccessor:

You might also need to register IHttpContextAccessor in ConfigureServices:

services.AddHttpContextAccessor();

参见 使用来自自定义组件的 HttpContext 以获取有关使用 IHttpContextAccessor 的更多信息.

See Use HttpContext from custom components for more information about using IHttpContextAccessor.

这篇关于在 netcore api 3.1 中读取 AuthorizationFilterContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆