Home > OS >  How audience is validated in KeyCloak JWT access token?
How audience is validated in KeyCloak JWT access token?

Time:06-05

I have an angular app talking to .Net Core. KeyCloak is used as an Auth server.

Angular app gets access token, and use it call rest apis(.net core).

In this access token there is an aud field whose value is

"aud": [
    "realm-management",
    "account"
  ],

I thought this will be server name, but its the keycloak client names.

In the .net core I am validating this token with validations like this

builder.Services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(o =>
    {
        o.MetadataAddress = config.KeyCloakURL;
        o.RequireHttpsMetadata = false; // only for dev
        o.SaveToken = true;
        o.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidateAudience = true
        };
        o.Events = new JwtBearerEvents()
        {
            OnAuthenticationFailed = c =>
            {
                c.NoResult();
                return c.Response.WriteAsync("An error occured processing your authentication.");
            }
        };
    });

I wonder how validation of the audience takes place.

Can any one tell me how the validate audience works here? What does it validate with?

CodePudding user response:

Figured it out. There is a 'ValidAudience' field which needs to be initialized.

new TokenValidationParameters()
        {
            ValidAudience = "realm-management",
            ValidateAudience = true
        }

I am not sure about the exact use case of this in KeyCloak's terms.

CodePudding user response:

The audience claim carries the information about who is intended to use the token. In case of access tokens it is usually the API that is the intended audience of the token. In case of ID tokens, it is usually the client. The Authorization Server is the issuer of the token, usually it will not be the audience. The concrete values that can end up in that claim are defined by the Authorization Server and should be meaningful to the intended audiences. For example, your API knows that it is part of the "account" audience and it expects this value in the audience claim. An API should reject tokens that have an unknown audience for security reasons.

Very often the audience is the URL of the API for which access tokens are issued. For ID tokens usually the client ID is used for the aud claim.

If you have control over the Authorization Server, then you are responsible for designing the audience values. These should reflect the needs of your APIs.

  • Related