39

I have an Asp.Net Core 2.0 WebApi which is authenticating against AAD:

            services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; })
                .AddJwtBearer(options =>
                            {
                                options.Authority = "https://login.microsoftonline.com/TENANT.onmicrosoft.com";
                                options.Audience = "CLIENT_ID";
                            });

My SPA app gets the token from AAD and sent it as bearer header. All works fine.

I have create a Job in Azure Scheduler and setup Active Directory OAuth: Job - Active Directory OAuth

After running a job I get this error: Bearer error="invalid_token", error_description="The audience is invalid".

When I set options.Audience in AddJwtBearer(...) to https://management.core.windows.net/ the Job works but not the SPA.

I guess, I need to set Audience to an array ['CLIENT_ID', "https://management.core.windows.net/"] but the options.Audience is type of string. If I don't set Audience at all, both Spa and Job does not work (401 unauthenticated). Setting Audience to CLIENT_ID,https://management.core.windows.net/ does not work either.

Is there a way how to enable multiple audiences in AddJwtBearer?

Skorunka František
  • 5,102
  • 7
  • 44
  • 69

1 Answers1

97

I think I ran into the same problem as you. To make it work I moved audience from options and into the TokenValidationParameters, which accepts multiple entries. Check the code below:

.AddJwtBearer(options =>
{
    options.Authority = "https://login.windows.net/trades.no";
    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidAudiences = new List<string> 
        {
            "AUDIENCE1",
            "AUDIENCE2" 
        }
    };
Pantani
  • 1,223
  • 1
  • 18
  • 25
  • 3
    That's exactly what I was looking for. Works. Thank you. – Skorunka František Nov 05 '17 at 13:18
  • Thanks this helped and it may be useful for folks to also understand when these configuration settings are needed depending on if app registration authentication is set for my org, any org or any org or consumer signins as discussed in https://stackoverflow.com/questions/53966951/asp-net-core-azureadjwtbearer-issuer-validation-failure/53973136 – myusrn Dec 29 '18 at 20:33
  • Could you please look into the scenario mentioned in https://stackoverflow.com/questions/55606855/jwt-bearer-token-validation-parameter-for-each-port-net-core-kestral – Harsh Sharma Apr 12 '19 at 11:01