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?
1
This should not be the answer, but it is the best thing I have discovered. I can use the OnMessageReceived event handler to manually parse the token out of the authentication header using my custom scheme name, instead of “Bearer “.
This is based on an answer I found at /a/73620848.
Why does the default behavior of AddJwtBearer not already do this?
options.Events.OnMessageReceived = async context => {
// AddJwtBearer only works if scheme of token is "Bearer". This custom logic will allow the token to be parsed
// when using a custom scheme.
// if scheme is default "Bearer", skip custom logic, because base behavior already works
if (!string.Equals(context.Scheme.Name, JwtBearerDefaults.AuthenticationScheme)
&& string.Equals(context.Scheme.Name, AuthenticationScheme, StringComparison.OrdinalIgnoreCase))
{
// only perform if it is the configured scheme
var authorization = context?.Request.Headers?["Authorization"] ?? new Microsoft.Extensions.Primitives.StringValues();
var testString = $"{AuthenticationScheme} ";
var matchingAuthorization = authorization.FirstOrDefault(a => a.StartsWith(testString, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrWhiteSpace(matchingAuthorization))
{
context.Token = matchingAuthorization.Substring(testString.Length).Trim();
}
}
};