0
votes

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?

1

1 Answers

7
votes

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 AddJwtBerer registers a scheme named "AzureAd" instead.

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.