Why I need to specify AuthenticationSchemes although I have set the defaultScheme?

Viewed 24

I'm developing a Web-Api in .NET 6, and I'm trying to use JWT for authentication.

In my Program.cs file, I've added the authentication as follows:

builder.Services
    .AddAuthentication(defaultScheme: JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = builder.Configuration["JwtSettings:Issuer"],
        ValidAudience = builder.Configuration["JwtSettings:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JwtSettings:SigningKey"])),
    });

and I'm using the [Authorize] attribute on the methods I want to protect.

This works only if I specify the authentication scheme like this: [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

What am I doing wrong setting up the default authentication scheme so I can use the [Authorize] attribute as is.

Thanks in advance.

1 Answers

Try this!

You need to add app.UseAuthentication() in program.cs because there is no authentication middleware now.

Related