I'm trying to set my custom authentication handler as default, so that I can use [Authorize] attribute without explicitly specifying the scheme. Here is the Program.cs code:
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services
.AddAuthentication(Constants.Auth.SchemeNames.MyScheme) // <-- why doesn't it work?
.AddScheme<CustomAuthenticationSchemeOptions, CustomAuthenticationHandler>(Constants.Auth.SchemeNames.MyScheme, null);
builder.Services.AddControllers();
var app = builder.Build();
app.UseAuthorization();
app.MapControllers();
app.Run();
But the CustomAuthenticationHandler.HandleAuthenticateAsync() method is called only if I specify my scheme name in the attributes explicitly:
[Authorize(AuthenticationSchemes = Constants.Auth.SchemeNames.MyScheme)]
Why is the default schema name not applied in the AddAuthentication method?
ASP.NET Core ver = 6.0.8
P.S.
I've set up the authorization default policy:
builder.Services.AddAuthorization(cfg =>
{
var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(Constants.Auth.SchemeNames.MyScheme);
defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser();
cfg.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build();
});
And now my scheme is used by default as I wanted, but I still can't understand what is the role of the string defaultScheme parameter in the AddAuthentication method:
public static AuthenticationBuilder AddAuthentication(this IServiceCollection services, string defaultScheme)
Now it works even if I don't pass the defaultScheme to it at all.
Another strange thing is that even when my CustomAuthenticationHandler is not called, the [Authorize] attribute still seems to work somehow since the 401 code is returned. It looks like some default authentication scheme is in charge even if I haven't set anything except my custom one.