默认的挑战方案在RouteGroups中无法工作?

huangapple go评论80阅读模式
英文:

Default challenge scheme isn't working with RouteGroups?

问题

我有一个用于多个端点的路由组:

internal class EmployeeRouteGroup : RouteGroup
{
    /// <inheritdoc />
    protected override string Prefix => "employees";

    /// <inheritdoc />
    protected override RouteGroupBuilder ConfigureCommonBehaviour(RouteGroupBuilder routeGroupBuilder)
    {
        return routeGroupBuilder.RequireAuthorization();
    }

    /// <inheritdoc />
    protected override RouteGroupBuilder ConfigureRoutes(RouteGroupBuilder routeGroupBuilder)
    {
        routeGroupBuilder.MapGet("/", async ([AsParameters] SearchEmployeesParametersDto getEmployeesParameters, IMediator mediator, CancellationToken cancellationToken)
            => await mediator.Send(new SearchEmployeesQuery { Parameters = getEmployeesParameters }, cancellationToken));

        routeGroupBuilder.MapGet("/{id}", async (int id, IMediator mediator, CancellationToken cancellationToken)
            => await mediator.Send(new GetEmployeeDetailsQuery { EmployeeId = id }, cancellationToken));

        routeGroupBuilder.MapGet("/for-salary-access-user/{id}", async (int id, IMediator mediator, CancellationToken cancellationToken)
            => await mediator.Send(new SearchEmployeesForSalaryAccessUserQuery { SalaryAccessUserId = id }, cancellationToken));

        return routeGroupBuilder;
    }
}

还在 Startup.cs 中设置了 DefaultChallengeScheme

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o => o = jwtOptions);

但每次尝试进行未授权的请求时,都会收到 404 响应而不是 401

如果在端点内部放置 [Authorize(AuthenticationScheme = ...)] 则可以正常工作!但是,您知道,这不是一个好方法 默认的挑战方案在RouteGroups中无法工作?

英文:

I have a Route Group for several endpoints:

internal class EmployeeRouteGroup : RouteGroup
{
    /// &lt;inheritdoc /&gt;
    protected override string Prefix =&gt; &quot;employees&quot;;

    /// &lt;inheritdoc /&gt;
    protected override RouteGroupBuilder ConfigureCommonBehaviour(RouteGroupBuilder routeGroupBuilder)
    {
        return routeGroupBuilder.RequireAuthorization();
    }

    /// &lt;inheritdoc /&gt;
    protected override RouteGroupBuilder ConfigureRoutes(RouteGroupBuilder routeGroupBuilder)
    {
        routeGroupBuilder.MapGet(&quot;/&quot;, async ([AsParameters] SearchEmployeesParametersDto getEmployeesParameters, IMediator mediator, CancellationToken cancellationToken)
            =&gt; await mediator.Send(new SearchEmployeesQuery { Parameters = getEmployeesParameters }, cancellationToken));

        routeGroupBuilder.MapGet(&quot;/{id}&quot;, async (int id, IMediator mediator, CancellationToken cancellationToken)
            =&gt; await mediator.Send(new GetEmployeeDetailsQuery { EmployeeId = id }, cancellationToken));

        routeGroupBuilder.MapGet(&quot;/for-salary-access-user/{id}&quot;, async (int id, IMediator mediator, CancellationToken cancellationToken)
            =&gt; await mediator.Send(new SearchEmployeesForSalaryAccessUserQuery { SalaryAccessUserId = id }, cancellationToken));

        return routeGroupBuilder;
    }
}

Also in Startup.cs I've setup DefaultChallengeScheme:

services.AddAuthentication(options =&gt;
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o =&gt; o = jwtOptions);

But everytime when I'm trying to make unauthorized request I get 404 response instead of 401.

If you put [Authorize(AuthenticationScheme = ...)] within endpoint it works fine! But, you know, it's not good approach 默认的挑战方案在RouteGroups中无法工作?

答案1

得分: 1

问题实际上是在 Authentication 设置之后存在一个 Identity 设置。

AddIdentity&lt;&gt; 方法包含以下代码:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
    options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
    options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddCookie(IdentityConstants.ApplicationScheme, o =>
{
    o.LoginPath = new PathString("/Account/Login");
    o.Events = new CookieAuthenticationEvents
    {
        OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync
    };
})

因此,要解决这个问题,您只需要在设置 Identity 之后设置您的身份验证。

英文:

The problem was in fact that there was an Identity setup after Authentication setup.

AddIdentity&lt;&gt; method contains this code:

services.AddAuthentication(options =&gt;
        {
            options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
            options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
            options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
        })
        .AddCookie(IdentityConstants.ApplicationScheme, o =&gt;
        {
            o.LoginPath = new PathString(&quot;/Account/Login&quot;);
            o.Events = new CookieAuthenticationEvents
            {
                OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync
            };
        })

So, to solve this issue you have to just setup your Authentication after Identity.

huangapple
  • 本文由 发表于 2023年7月20日 13:49:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76727003.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定