JSON Web Tokens (JWT)

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way to securely transmit information between parties as a JSON object. JWTs are widely used for authentication and authorization in web applications, APIs, and microservices.

A JWT consists of three parts: a header, a payload, and a signature. The header typically specifies the token type and the signing algorithm. The payload contains the claims - information such as user identity, permissions, or other metadata. The signature ensures the integrity and authenticity of the token, verifying that it has not been altered during transmission.

JWTs are a key component in OAuth 2.0 and OpenID Connect (OIDC) flows, where they securely convey user identity and authorization data between the client and the authorization server.

One of the main advantages of JWTs is that they are stateless, meaning that the server does not need to store session data. This property makes them ideal for microservices and distributed environments.

From a security perspective, JWTs are considered secure when the signature is properly implemented and verified. The signing key - known only to the issuing server - ensures that tokens cannot be tampered with or forged.

Adding a Custom JWT Claim

Once the application has been secured using OIDC (see section 2.1.2 - Securing Quarkus web applications using OpenID Connect (OIDC)), we may need to include a custom claim in the JWT token based on a user attribute. This allows us to use that attribute for fine-grained authorization in the application.

  • Open the Red Hat Single Sign-On administration console in a web browser.

  • Navigate to Clients → select the quarkus-petclinic client in the Demo realm.

  • Click on the Mappers tab and click Create.

mapper1
  • Configure the mapper:

    • Mapper Type: User attribute

    • User Attribute: the attribute you want to map (for example, admin)

    • Token Claim Name: choose the claim name for the JSON payload

    • Claim JSON Type: select the data type (for example, boolean)

    • Add to ID token: ON if you want it included in the ID token

Once completed, click Save.

mapper2
  • Add the attribute to a test user:

    • Navigate to UsersView all users → select the user angel.

    • Click on the Attributes tab.

    • Fill in the admin field (or other attribute), click Add, then click Save.

edit user
new user attr

Verifying the Claim

After logging in to the application with an authorized user, the custom claim should now be present in the JWT. You can inspect it from the Quarkus application by injecting the JsonWebToken via CDI, or using any valid JWT inspection method.

eyJhbGciOiJS...xmRqTndw

Decoding the JWT should reveal the new attribute:

{
  "alg": "RS256",
  ...
}
{
  ...
  "azp": "quarkus-petclinic",
  ...
  "realm_access": {
    "roles": [
      "vet"
    ]
  },
  ...
  "admin": true,
  "preferred_username": "angel"
}
{
  ...
}