'No authenticationScheme was specified error even when JWT Authentication Specified
I'm new to AzureAD authentication. I setup my Web API with below settings in startup.cs
services.AddAuthentication(sharedopt => sharedopt.DefaultScheme = JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer("AzureAd", options =>
{
options.Audience = Configuration.GetValue<string>("AzureAd:Audience");
options.Authority = Configuration.GetValue<string>("AzureAd:Instance")
+ Configuration.GetValue<string>("AzureAd:TenantId");
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
{
ValidIssuer = Configuration.GetValue<string>("AzureAd:Issuer"),
ValidAudience = Configuration.GetValue<string>("AzureAd:Audience")
};
});
I am expecting my Client App (Angular) will attach Authorization header in its requests and thus it will get access to API
But when I execute the Web API and trying to open any API with Authorize, it triggers this error
InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action configureOptions).
I already specified JWTBearerDefaults.AuthenticationScheme. Still why its not accepting?
Solution 1:[1]
Please remove the first "AzureAd" parameter from AddJwtBearer call.
TLDR: When you call AddAuthentication you set the default scheme to JwtBearerDefaults.AuthenticationScheme which is string "Bearer".
This tells the authentication middleware to authenticate all requests (unless specified otherwise e.g. via Authorize attribute with schemes) to use a set of handlers and configurations organized by the shceme name "Bearer".
However you didn't register that scheme. Your call to AddJwtBearer registers a scheme named "AzureAd" instead of "Bearer".
Authentication middleware cannot find the matching scheme and hence the error.
If you don't specify the "AzureAd" parameter, below version of AddJwtBearer is invoked:
builder.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, configureOptions);
As we can see, it registers the JwtBearer authentication with scheme "Bearer" matching your default scheme.
Solution 2:[2]
You might have missed to register services.ConfigureApiAuthentication(Configuration); in the startup class
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeff L |
| Solution 2 | Thomas Raj |
