My ultimate goal is to implement multiple authentication schemes in ASP.Net Core, but I cannot even seem to get a single custom scheme to work. I have included excerpts of my code below. You will see that I have hard coded "Bearer" as the scheme in 3 places. This completely works every time. However, if I change these 3 instances from "Bearer" to "Scheme2", it fails, because the service does not authenticate the user. I can clearly see this in the dubugger where the User.IsAuthenticated flag is false.
I am following the instructions at this site. https://learn.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme?view=aspnetcore-8.0
What step am I misssing? Why does my service properly authenticate the user as long as I name the scheme "Bearer", but fails to authenticate with any other name?
Error:
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService: Information: Authorization failed. These requirements were not met: DenyAnonymousAuthorizationRequirement: Requires an authenticated user. Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Information: Authorization failed for the request at filter 'MyCustomFilter'. Microsoft.AspNetCore.Mvc.ChallengeResult: Information: Executing ChallengeResult with authentication schemes (Scheme2). Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler: Information: AuthenticationScheme: Scheme2 was challenged.
Provide Bearer Token to HttpRequestMessage:
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "access token");
App Startup:
builder.Services.AddAuthentication();
.AddJwtBearer("Bearer", options =>
{
options.Authority = "Authority";
options.Audience = "Audience";
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
Provide to AuthorizeFilter:
var pb = new AuthorizationPolicyBuilder("Bearer").RequireAuthenticatedUser()
;
return pb.Build();
Update:
I added event handlers to AddJwtBearer, just to see what happens. With "Bearer", each service request calls OnMessageReceived followed by OnTokenValidated. However, with "Scheme2", each request calls OnMessageReceived followed by OnChallenge. I don't really know what this is telling me, other than that the JwtBearer authentication is failing with a scheme of "Scheme2". Is this a known thing? Should it care what the scheme name is?
app.UseAuthentication().AddJwtBearer(options => { // ... }).AddScheme<MyAuthenticationSchemeOptions, MyAuthenticationSchemeHandler>("MyName", options => { });- this doc might be more helpful: learn.microsoft.com/en-us/aspnet/core/security/authentication/…