How to set multiple audiences in Asp.Net Core 2.0 "AddJwtBearer" middleware?

Skorunka František picture Skorunka František · Oct 28, 2017 · Viewed 12.6k times · Source

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?

Answer

Pantani picture Pantani · Nov 2, 2017

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" 
        }
    };