dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.52k stars 10.04k forks source link

Default Authentication Scheme Not Honored with JwtBearerDefaults.AuthenticationScheme in .NET 8.0 #58906

Open ManoNero opened 6 days ago

ManoNero commented 6 days ago

Hi,

I'm using .NET 8.0 and encountering an issue with setting the default authentication scheme. Despite specifying JwtBearerDefaults.AuthenticationScheme as the default, it doesn't seem to be recognized in my controllers.

Authentication Configuration:

Here's how I've set up authentication in my Program.cs:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddCookie()
    .AddJwtBearer(options =>
    {
        options.Authority = configuration["Jwt:Authority"];
        options.RequireHttpsMetadata = configuration["Jwt:RequireHttpsMetadata"] == "true";
    });

Controller Setup:

In my controller, I'm using the [Authorize] attribute without specifying any scheme:

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class MyController : ControllerBase
{
    // Controller actions
}

Issue:

With the above setup, authentication doesn't work as expected. The [Authorize] attribute does not utilize the default scheme specified (JwtBearerDefaults.AuthenticationScheme). As a result, JWT authentication fails, and authorized endpoints are not accessible.

Workaround:

To make it work, I have to explicitly specify the authentication scheme in the [Authorize] attribute:

[ApiController]
[Route("api/[controller]")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class MyController : ControllerBase
{
    // Controller actions
}

Expected Behavior:

By setting the default authentication scheme using AddAuthentication(JwtBearerDefaults.AuthenticationScheme), I expect the [Authorize] attribute to automatically use this scheme without needing to specify it explicitly in every controller or action.

Actual Behavior:

The default authentication scheme is ignored unless explicitly specified in the [Authorize] attribute.

Questions:

Environment:

Any guidance on resolving this issue or clarification on whether this is intended behavior would be greatly appreciated.

Thank you!

danroth27 commented 1 day ago

Hi @ManoNero. To help us investigate this issue, could you please provide us a project that reproduces the problem?

dotnet-policy-service[bot] commented 1 day ago

Thank you for filing this issue. In order for us to investigate this issue, please provide a minimal repro project that illustrates the problem without unnecessary code. Please share with us in a public GitHub repo because we cannot open ZIP attachments, and don't include any confidential content.