Cannot get custom authentication scheme name to work with ASP.Net Core

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "access token");
</code>
<code>message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "access token"); </code>
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "access token");

App Startup:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>builder.Services.AddAuthentication();
.AddJwtBearer("Bearer", options =>
{
options.Authority = "Authority";
options.Audience = "Audience";
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
</code>
<code>builder.Services.AddAuthentication(); .AddJwtBearer("Bearer", options => { options.Authority = "Authority"; options.Audience = "Audience"; }); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization(); </code>
builder.Services.AddAuthentication();
         .AddJwtBearer("Bearer", options =>
         {
             options.Authority = "Authority";
             options.Audience = "Audience";
         });
                     
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization(); 

                 

Provide to AuthorizeFilter:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var pb = new AuthorizationPolicyBuilder("Bearer").RequireAuthenticatedUser()
;
return pb.Build();
</code>
<code>var pb = new AuthorizationPolicyBuilder("Bearer").RequireAuthenticatedUser() ; return pb.Build(); </code>
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?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> 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();
}
}
};
</code>
<code> 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(); } } }; </code>
                     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();
                             }

                         }
                     };

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật