For an ASP.NET WebAPI I'm trying to establish two authentication schemes (for JWTs) to protect different resources, since I cannot use a single authentication (for silly reasons, but I cannot do anything about it right now). Theoretically allowing two different schemes should be relatively straight forward, but for some reason it is not and I do not know what else I could try to make it work (basically, I'm following this guide). My approach was to call AddJwtBearer
twice in my setup with two different schemes
builder.Services.AddAuthentication()
.AddJwtBearer(
options =>
{
// ...
})
.AddJwtBearer(
AuthenticationDefaults.CustomScheme,
options =>
{
options.Challenge = AuthenticationDefaults.CustomScheme;
// ...
});
Furthermore I added
builder.Services.AddAuthorization(
options =>
{
var customPolicy = new AuthorizationPolicyBuilder(AuthenticationDefaults.CustomScheme)
.RequireAuthenticatedUser()
.Build();
var azureAdPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme).RequireAuthenticatedUser()
.Build();
options.AddPolicy(AuthenticationDefaults.CustomScheme, customPolicy);
options.AddPolicy(JwtBearerDefaults.AuthenticationScheme, azureAdPolicy);
options.DefaultPolicy = customPolicy;
});
to my setup and
[Authorize(AuthenticationSchemes = AuthenticationDefaults.CustomScheme)]
to my controller method.
Anyway, authorization with CustomScheme
does not work. The scheme/policy seems to be functional (theoretical), for if I pass the Authorization
header with my custom scheme, the WWW-Authenticate
header matches my type, but I always get a 401 Unauthorized
. When I add
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
to any controller method and pass a valid token for the configuration, I get a 200 OK
. I've checked the configuration for validating the tokens two and three times, but it seems okay. To me, the implementation seems broken, but then online people claim that something very similar worked out for them. Am I missing something?