Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 927
Skorunka František Avatar asked Oct 28 '17 13:10

Skorunka František


People also ask

Can a JWT have multiple audiences?

A JWT token can have several audiences, but the consumer of the token only identifies as a single audience.

Can you have more than one JWT token?

You can have only 1 JWT marketplace app registered in your account. However, you can generate multiple JWT tokens using the JWT keys, and the tokens operate independently of each other until expired or the credentials have been changed.

What is JwtBearer?

The JwtBearer middleware looks for tokens (JSON Web Tokens or JWTs) in the HTTP Authorization header of incoming requests. If a valid token is found, the request is authorized.


1 Answers

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" 
        }
    };
like image 189
Pantani Avatar answered Oct 22 '22 19:10

Pantani