Skip to content

.NET 7 UseAuthentication and UserAuthorization ordering not respected when within UseWhen #48098

@UniSnake

Description

@UniSnake

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

When configuring my WebApplication I make use of a UseWhen statement so that auth logic is only applied to endpoints with a specific base path.

This worked with ASP.NET Core 6.0 but with 7.0 there are two problems:

  1. Auth is applied to all endpoints.
  2. Auth middleware runs before all other middleware.

I believe this to be caused by the new 7.0 feature that automatically calls UseAuthentication and UseAuthorization when AddAuthentication / AddAuthorization are called. I see there is code in place to prevent this if it is detected that UseAuthentication / UseAuthentication have already been called, but this does not appear to take UseWhen into account.

Expected Behavior

Auth middleware is not inserted when already inserted within a UseWhen statement.

Steps To Reproduce

app.UseWhen(
    httpContext => httpContext.Request.Path.StartsWithSegments("/api"),
    subApp =>
    {
        subApp.UseAuthentication();
        subApp.UseAuthorization();
    });

Exceptions (if any)

No response

.NET Version

7.0.203

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-minimalIncludes minimal APIs, endpoint filters, parameter binding, request delegate generator etcbugThis issue describes a behavior which is not expected - a bug.feature-minimal-hosting

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions