OpenID Connect (OIDC) authentication


Red Hat build of Quarkus 3.20

Red Hat Customer Content Services

Abstract

This guide provides an in-depth look at OpenID Connect (OIDC) authentication, using bearer token authentication to protect service applications, OIDC authorization code flow to protect web applications, and OIDC multitenancy to support multiple OIDC providers and flows.

To report an error or to improve our documentation, log in to your Red Hat Jira account and submit an issue. If you do not have a Red Hat Jira account, then you will be prompted to create an account.

Procedure

  1. Click the following link to create a ticket.
  2. Enter a brief description of the issue in the Summary.
  3. Provide a detailed description of the issue or enhancement in the Description. Include a URL to where the issue occurs in the documentation.
  4. Clicking Submit creates and routes the issue to the appropriate documentation team.

Secure HTTP access to Jakarta REST (formerly known as JAX-RS) endpoints in your application with Bearer token authentication by using the Quarkus OpenID Connect (OIDC) extension.

Quarkus supports the Bearer token authentication mechanism through the Quarkus OpenID Connect (OIDC) extension.

The bearer tokens are issued by OIDC and OAuth 2.0 compliant authorization servers, such as Keycloak.

Bearer token authentication is the process of authorizing HTTP requests based on the existence and validity of a bearer token. The bearer token provides information about the subject of the call, which is used to determine whether or not an HTTP resource can be accessed.

The following diagrams outline the Bearer token authentication mechanism in Quarkus:

Figure 1.1. Bearer token authentication mechanism in Quarkus with single-page application

  1. The Quarkus service retrieves verification keys from the OIDC provider. The verification keys are used to verify the bearer access token signatures.
  2. The Quarkus user accesses the single-page application (SPA).
  3. The single-page application uses Authorization Code Flow to authenticate the user and retrieve tokens from the OIDC provider.
  4. The single-page application uses the access token to retrieve the service data from the Quarkus service.
  5. The Quarkus service verifies the bearer access token signature by using the verification keys, checks the token expiry date and other claims, allows the request to proceed if the token is valid, and returns the service response to the single-page application.
  6. The single-page application returns the same data to the Quarkus user.

Figure 1.2. Bearer token authentication mechanism in Quarkus with Java or command line client

  1. The Quarkus service retrieves verification keys from the OIDC provider. The verification keys are used to verify the bearer access token signatures.
  2. The client uses client_credentials that requires client id and secret or password grant, which requires client id, secret, username, and password to retrieve the access token from the OIDC provider.
  3. The client uses the access token to retrieve the service data from the Quarkus service.
  4. The Quarkus service verifies the bearer access token signature by using the verification keys, checks the token expiry date and other claims, allows the request to proceed if the token is valid, and returns the service response to the client.

If you need to authenticate and authorize users by using OIDC authorization code flow, see the Quarkus OpenID Connect authorization code flow mechanism for protecting web applications guide. Also, if you use Keycloak and bearer tokens, see the Quarkus Using Keycloak to centralize authorization guide.

To learn about how you can protect service applications by using OIDC Bearer token authentication, see the following tutorial:

For information about how to support multiple tenants, see the Quarkus Using OpenID Connect Multi-Tenancy guide.

1.1.1. Accessing JWT claims

If you need to access JWT token claims, you can inject JsonWebToken:

package org.acme.security.openid.connect;

import org.eclipse.microprofile.jwt.JsonWebToken;
import jakarta.inject.Inject;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;

@Path("/api/admin")
public class AdminResource {

    @Inject
    JsonWebToken jwt;

    @GET
    @RolesAllowed("admin")
    @Produces(MediaType.TEXT_PLAIN)
    public String admin() {
        return "Access for subject " + jwt.getSubject() + " is granted";
    }
}
Copy to Clipboard Toggle word wrap

Injection of JsonWebToken is supported in @ApplicationScoped, @Singleton, and @RequestScoped scopes. However, the use of @RequestScoped is required if the individual claims are injected as simple types. For more information, see the Supported injection scopes section of the Quarkus "Using JWT RBAC" guide.

1.1.2. UserInfo

If you must request a UserInfo JSON object from the OIDC UserInfo endpoint, set quarkus.oidc.authentication.user-info-required=true. A request is sent to the OIDC provider UserInfo endpoint, and an io.quarkus.oidc.UserInfo (a simple javax.json.JsonObject wrapper) object is created. io.quarkus.oidc.UserInfo can be injected or accessed as a SecurityIdentity userinfo attribute.

quarkus.oidc.authentication.user-info-required is automatically enabled if one of these conditions is met:

  • if quarkus.oidc.roles.source is set to userinfo or quarkus.oidc.token.verify-access-token-with-user-info is set to true or quarkus.oidc.authentication.id-token-required is set to false, the current OIDC tenant must support a UserInfo endpoint in these cases.
  • if io.quarkus.oidc.UserInfo injection point is detected but only if the current OIDC tenant supports a UserInfo endpoint.

1.1.3. Configuration metadata

The current tenant’s discovered OpenID Connect Configuration Metadata is represented by io.quarkus.oidc.OidcConfigurationMetadata and can be injected or accessed as a SecurityIdentity configuration-metadata attribute.

The default tenant’s OidcConfigurationMetadata is injected if the endpoint is public.

1.1.4. Token claims and SecurityIdentity roles

You can map SecurityIdentity roles from the verified JWT access tokens as follows:

  • If the quarkus.oidc.roles.role-claim-path property is set, and matching array or string claims are found, then the roles are extracted from these claims. For example, customroles, customroles/array, scope, "http://namespace-qualified-custom-claim"/roles, "http://namespace-qualified-roles".
  • If a groups claim is available, then its value is used.
  • If a realm_access/roles or resource_access/client_id/roles (where client_id is the value of the quarkus.oidc.client-id property) claim is available, then its value is used. This check supports the tokens issued by Keycloak.

For example, the following JWT token has a complex groups claim that contains a roles array that includes roles:

{
    "iss": "https://server.example.com",
    "sub": "24400320",
    "upn": "jdoe@example.com",
    "preferred_username": "jdoe",
    "exp": 1311281970,
    "iat": 1311280970,
    "groups": {
        "roles": [
          "microprofile_jwt_user"
        ],
    }
}
Copy to Clipboard Toggle word wrap

You must map the microprofile_jwt_user role to SecurityIdentity roles, and you can do so with this configuration: quarkus.oidc.roles.role-claim-path=groups/roles.

If the token is opaque (binary), then a scope property from the remote token introspection response is used.

If UserInfo is the source of the roles, then set quarkus.oidc.authentication.user-info-required=true and quarkus.oidc.roles.source=userinfo, and if needed, set quarkus.oidc.roles.role-claim-path.

Additionally, a custom SecurityIdentityAugmentor can also be used to add the roles. For more information, see the Security identity customization section of the Quarkus "Security tips and tricks" guide.

You can also map SecurityIdentity roles created from token claims to deployment-specific roles by using the HTTP Security policy.

SecurityIdentity permissions are mapped in the form of io.quarkus.security.StringPermission from the scope parameter of the source of the roles and using the same claim separator.

import java.util.List;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;

import org.eclipse.microprofile.jwt.Claims;
import org.eclipse.microprofile.jwt.JsonWebToken;

import io.quarkus.security.PermissionsAllowed;

@Path("/service")
public class ProtectedResource {

    @Inject
    JsonWebToken accessToken;

    @PermissionsAllowed("email") 
1

    @GET
    @Path("/email")
    public Boolean isUserEmailAddressVerifiedByUser() {
        return accessToken.getClaim(Claims.email_verified.name());
    }

    @PermissionsAllowed("orders_read") 
2

    @GET
    @Path("/order")
    public List<Order> listOrders() {
        return List.of(new Order("1"));
    }

    public static class Order {
        String id;
        public Order() {
        }
        public Order(String id) {
            this.id = id;
        }
        public String getId() {
            return id;
        }
        public void setId() {
            this.id = id;
        }
    }
}
Copy to Clipboard Toggle word wrap
1
Only requests with OpenID Connect scope email will be granted access.
2
The read access is limited to the client requests with the orders_read scope.

For more information about the io.quarkus.security.PermissionsAllowed annotation, see the Permission annotation section of the "Authorization of web endpoints" guide.

1.1.6. Token verification and introspection

If the token is a JWT token, then, by default, it is verified with a JsonWebKey (JWK) key from a local JsonWebKeySet, retrieved from the OIDC provider’s JWK endpoint. The token’s key identifier (kid) header value is used to find the matching JWK key. If no matching JWK is available locally, then JsonWebKeySet is refreshed by fetching the current key set from the JWK endpoint. The JsonWebKeySet refresh can be repeated only after the quarkus.oidc.token.forced-jwk-refresh-interval expires. The default expiry time is 10 minutes. If no matching JWK is available after the refresh, the JWT token is sent to the OIDC provider’s token introspection endpoint.

If the token is opaque, which means it can be a binary token or an encrypted JWT token, then it is always sent to the OIDC provider’s token introspection endpoint.

If you work only with JWT tokens and expect a matching JsonWebKey to always be available, for example, after refreshing a key set, you must disable token introspection, as shown in the following example:

quarkus.oidc.token.allow-jwt-introspection=false
quarkus.oidc.token.allow-opaque-token-introspection=false
Copy to Clipboard Toggle word wrap

There might be cases where JWT tokens must be verified through introspection only, which can be forced by configuring an introspection endpoint address only. The following properties configuration shows you an example of how you can achieve this with Keycloak:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.oidc.discovery-enabled=false
# Token Introspection endpoint: http://localhost:8180/realms/quarkus/protocol/openid-connect/tokens/introspect
quarkus.oidc.introspection-path=/protocol/openid-connect/tokens/introspect
Copy to Clipboard Toggle word wrap

There are advantages and disadvantages to indirectly enforcing the introspection of JWT tokens remotely. An advantage is that you eliminate the need for two remote calls: a remote OIDC metadata discovery call followed by another remote call to fetch the verification keys that will not be used. A disadvantage is that you need to know the introspection endpoint address and configure it manually.

The alternative approach is to allow the default option of OIDC metadata discovery but also require that only the remote JWT introspection is performed, as shown in the following example:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.oidc.token.require-jwt-introspection-only=true
Copy to Clipboard Toggle word wrap

An advantage of this approach is that the configuration is simpler and easier to understand. A disadvantage is that a remote OIDC metadata discovery call is required to discover an introspection endpoint address, even though the verification keys will not be fetched.

The io.quarkus.oidc.TokenIntrospection, a simple jakarta.json.JsonObject wrapper object, will be created. It can be injected or accessed as a SecurityIdentity introspection attribute, providing either the JWT or opaque token has been successfully introspected.

1.1.7. Token introspection and UserInfo cache

All opaque access tokens must be remotely introspected. Sometimes, JWT access tokens might also have to be introspected. If UserInfo is also required, the same access token is used in a subsequent remote call to the OIDC provider. So, if UserInfo is required, and the current access token is opaque, two remote calls are made for every such token; one remote call to introspect the token and another to get UserInfo. If the token is JWT, only a single remote call to get UserInfo is needed, unless it also has to be introspected.

The cost of making up to two remote calls for every incoming bearer or code flow access token can sometimes be problematic.

If this is the case in production, consider caching the token introspection and UserInfo data for a short period, for example, 3 or 5 minutes.

quarkus-oidc provides quarkus.oidc.TokenIntrospectionCache and quarkus.oidc.UserInfoCache interfaces, usable for @ApplicationScoped cache implementation. Use @ApplicationScoped cache implementation to store and retrieve quarkus.oidc.TokenIntrospection and/or quarkus.oidc.UserInfo objects, as outlined in the following example:

@ApplicationScoped
@Alternative
@Priority(1)
public class CustomIntrospectionUserInfoCache implements TokenIntrospectionCache, UserInfoCache {
...
}
Copy to Clipboard Toggle word wrap

Each OIDC tenant can either permit or deny the storing of its quarkus.oidc.TokenIntrospection data, quarkus.oidc.UserInfo data, or both with boolean quarkus.oidc."tenant".allow-token-introspection-cache and quarkus.oidc."tenant".allow-user-info-cache properties.

Additionally, quarkus-oidc provides a simple default memory-based token cache, which implements both quarkus.oidc.TokenIntrospectionCache and quarkus.oidc.UserInfoCache interfaces.

You can configure and activate the default OIDC token cache as follows:

# 'max-size' is 0 by default, so the cache can be activated by setting 'max-size' to a positive value:
quarkus.oidc.token-cache.max-size=1000
# 'time-to-live' specifies how long a cache entry can be valid for and will be used by a cleanup timer:
quarkus.oidc.token-cache.time-to-live=3M
# 'clean-up-timer-interval' is not set by default, so the cleanup timer can be activated by setting 'clean-up-timer-interval':
quarkus.oidc.token-cache.clean-up-timer-interval=1M
Copy to Clipboard Toggle word wrap

The default cache uses a token as a key, and each entry can have TokenIntrospection, UserInfo, or both. It will only keep up to a max-size number of entries. If the cache is already full when a new entry is to be added, an attempt is made to find a space by removing a single expired entry. Additionally, the cleanup timer, if activated, periodically checks for expired entries and removes them.

You can experiment with the default cache implementation or register a custom one.

1.1.8. JSON Web Token claim verification

After the bearer JWT token’s signature has been verified and its expires at (exp) claim has been checked, the iss (issuer) claim value is verified next.

By default, the iss claim value is compared to the issuer property, which might have been discovered in the well-known provider configuration. However, if the quarkus.oidc.token.issuer property is set, then the iss claim value is compared to it instead.

In some cases, this iss claim verification might not work. For example, if the discovered issuer property contains an internal HTTP/IP address while the token iss claim value contains an external HTTP/IP address. Or when a discovered issuer property contains the template tenant variable, but the token iss claim value has the complete tenant-specific issuer value.

In such cases, consider skipping the issuer verification by setting quarkus.oidc.token.issuer=any. Only skip the issuer verification if no other options are available:

  • If you are using Keycloak and observe the issuer verification errors caused by the different host addresses, configure Keycloak with a KEYCLOAK_FRONTEND_URL property to ensure the same host address is used.
  • If the iss property is tenant-specific in a multitenant deployment, use the SecurityIdentity tenant-id attribute to check that the issuer is correct in the endpoint or the custom Jakarta filter. For example:
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.Provider;

import org.eclipse.microprofile.jwt.JsonWebToken;
import io.quarkus.oidc.OidcConfigurationMetadata;
import io.quarkus.security.identity.SecurityIdentity;

@Provider
public class IssuerValidator implements ContainerRequestFilter {
    @Inject
    OidcConfigurationMetadata configMetadata;

    @Inject JsonWebToken jwt;
    @Inject SecurityIdentity identity;

    public void filter(ContainerRequestContext requestContext) {
        String issuer = configMetadata.getIssuer().replace("{tenant-id}", identity.getAttribute("tenant-id"));
        if (!issuer.equals(jwt.getIssuer())) {
            requestContext.abortWith(Response.status(401).build());
        }
    }
}
Copy to Clipboard Toggle word wrap
Note

Consider using the quarkus.oidc.token.audience property to verify the token aud (audience) claim value.

1.1.9. Jose4j Validator

You can register a custom Jose4j Validator to customize the JWT claim verification process, before org.eclipse.microprofile.jwt.JsonWebToken is initialized. For example:

package org.acme.security.openid.connect;

import static org.eclipse.microprofile.jwt.Claims.iss;

import io.quarkus.arc.Unremovable;
import jakarta.enterprise.context.ApplicationScoped;

import org.jose4j.jwt.MalformedClaimException;
import org.jose4j.jwt.consumer.JwtContext;
import org.jose4j.jwt.consumer.Validator;

@Unremovable
@ApplicationScoped
public class IssuerValidator implements Validator { 
1


    @Override
    public String validate(JwtContext jwtContext) throws MalformedClaimException {
        if (jwtContext.getJwtClaims().hasClaim(iss.name())
                && "my-issuer".equals(jwtContext.getJwtClaims().getClaimValueAsString(iss.name()))) {
            return "wrong issuer"; 
2

        }
        return null; 
3

    }
}
Copy to Clipboard Toggle word wrap
1
Register Jose4j Validator to verify JWT tokens for all OIDC tenants.
2
Return the claim verification error description.
3
Return null to confirm that this Validator has successfully verified the token.
Tip

Use a @quarkus.oidc.TenantFeature annotation to bind a custom Validator to a specific OIDC tenant only.

1.1.10. Single-page applications

A single-page application (SPA) typically uses XMLHttpRequest(XHR) and the JavaScript utility code provided by the OIDC provider to acquire a bearer token to access Quarkus service applications.

For example, if you work with Keycloak, you can use keycloak.js to authenticate users and refresh the expired tokens from the SPA:

<html>
<head>
    <title>keycloak-spa</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script type="importmap">
        {
            "imports": {
                "keycloak-js": "https://cdn.jsdelivr.net/npm/keycloak-js@26.0.7/lib/keycloak.js"
            }
        }
    </script>
    <script type="module">
        import Keycloak from "keycloak-js";

        const keycloak = new Keycloak({
            url: 'http://localhost:8180',
            realm: 'quarkus',
            clientId: 'quarkus-app'
        });

        await keycloak.init({onLoad: 'login-required'}).then(function () {
            console.log('User is now authenticated.');
        }).catch(function () {
            console.log('User is NOT authenticated.');
        });

        function makeAjaxRequest() {
            axios.get("/api/hello", {
                headers: {
                    'Authorization': 'Bearer ' + keycloak.token
                }
            })
            .then( function (response) {
                console.log("Response: ", response.status);
            }).catch(function (error) {
                console.log('refreshing');
                keycloak.updateToken(5).then(function () {
                    console.log('Token refreshed');
                }).catch(function () {
                    console.log('Failed to refresh token');
                    window.location.reload();
                });
            });
        }

        let button = document.getElementById('ajax-request');
        button.addEventListener('click', makeAjaxRequest);
    </script>
</head>
<body>
    <button id="ajax-request">Request</button>
</body>
</html>
Copy to Clipboard Toggle word wrap
Note

To enable authentication for this SPA Keycloak example, disable Client authentication and set Web origins to http://localhost:8080. These settings allow Keycloak’s CORS policy to communicate with your Quarkus application. The code provides an example of building Quarkus single-page applications integrated with Keycloak. For more details about creating single-page applications integrating Keycloak, refer to the official Keycloak JavaScript adapter documentation.

1.1.11. Cross-origin resource sharing

If you plan to use your OIDC service application from a single-page application running on a different domain, you must configure cross-origin resource sharing (CORS). For more information, see the CORS filter section of the "Cross-origin resource sharing" guide.

1.1.12. Provider endpoint configuration

An OIDC service application needs to know the OIDC provider’s token, JsonWebKey (JWK) set, and possibly UserInfo and introspection endpoint addresses.

By default, they are discovered by adding a /.well-known/openid-configuration path to the configured quarkus.oidc.auth-server-url.

Alternatively, if the discovery endpoint is not available, or if you want to save on the discovery endpoint round-trip, you can disable the discovery and configure them with relative path values. For example:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.oidc.discovery-enabled=false
# Token endpoint: http://localhost:8180/realms/quarkus/protocol/openid-connect/token
quarkus.oidc.token-path=/protocol/openid-connect/token
# JWK set endpoint: http://localhost:8180/realms/quarkus/protocol/openid-connect/certs
quarkus.oidc.jwks-path=/protocol/openid-connect/certs
# UserInfo endpoint: http://localhost:8180/realms/quarkus/protocol/openid-connect/userinfo
quarkus.oidc.user-info-path=/protocol/openid-connect/userinfo
# Token Introspection endpoint: http://localhost:8180/realms/quarkus/protocol/openid-connect/tokens/introspect
quarkus.oidc.introspection-path=/protocol/openid-connect/tokens/introspect
Copy to Clipboard Toggle word wrap

1.1.13. Token propagation

For information about bearer access token propagation to the downstream services, see the Token propagation section of the Quarkus "OpenID Connect (OIDC) and OAuth2 client and filters reference" guide.

1.1.14. JWT token certificate chain

In some cases, JWT bearer tokens have an x5c header which represents an X509 certificate chain whose leaf certificate contains a public key that must be used to verify this token’s signature. Before this public key can be accepted to verify the signature, the certificate chain must be validated first. The certificate chain validation involves several steps:

  1. Confirm that every certificate but the root one is signed by the parent certificate.
  2. Confirm the chain’s root certificate is also imported in the truststore.
  3. Validate the chain’s leaf certificate. If a common name of the leaf certificate is configured then a common name of the chain’s leaf certificate must match it. Otherwise the chain’s leaf certificate must also be avaiable in the truststore, unless one or more custom TokenCertificateValidator implementations are registered.
  4. quarkus.oidc.TokenCertificateValidator can be used to add a custom certificate chain validation step. It can be used by all tenants expecting tokens with the certificate chain or bound to specific OIDC tenants with the @quarkus.oidc.TenantFeature annotation.

For example, here is how you can configure Quarkus OIDC to verify the token’s certificate chain, without using quarkus.oidc.TokenCertificateValidator:

quarkus.oidc.certificate-chain.trust-store-file=truststore-rootcert.p12 
1

quarkus.oidc.certificate-chain.trust-store-password=storepassword
quarkus.oidc.certificate-chain.leaf-certificate-name=www.quarkusio.com 
2
Copy to Clipboard Toggle word wrap
1
The truststore must contain the certificate chain’s root certificate.
2
The certificate chain’s leaf certificate must have a common name equal to www.quarkusio.com. If this property is not configured then the truststore must contain the certificate chain’s leaf certificate unless one or more custom TokenCertificateValidator implementations are registered.

You can add a custom certificate chain validation step by registering a custom quarkus.oidc.TokenCertificateValidator, for example:

package io.quarkus.it.keycloak;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;

import jakarta.enterprise.context.ApplicationScoped;

import io.quarkus.arc.Unremovable;
import io.quarkus.oidc.OidcTenantConfig;
import io.quarkus.oidc.TokenCertificateValidator;
import io.quarkus.oidc.runtime.TrustStoreUtils;
import io.vertx.core.json.JsonObject;

@ApplicationScoped
@Unremovable
public class BearerGlobalTokenChainValidator implements TokenCertificateValidator {

    @Override
    public void validate(OidcTenantConfig oidcConfig, List<X509Certificate> chain, String tokenClaims) throws CertificateException {
        String rootCertificateThumbprint = TrustStoreUtils.calculateThumprint(chain.get(chain.size() - 1));
        JsonObject claims = new JsonObject(tokenClaims);
        if (!rootCertificateThumbprint.equals(claims.getString("root-certificate-thumbprint"))) { 
1

            throw new CertificateException("Invalid root certificate");
        }
    }
}
Copy to Clipboard Toggle word wrap
1
Confirm that the certificate chain’s root certificate is bound to the custom JWT token’s claim.

1.1.15. OIDC provider client authentication

quarkus.oidc.runtime.OidcProviderClient is used when a remote request to an OIDC provider is required. If introspection of the Bearer token is necessary, then OidcProviderClient must authenticate to the OIDC provider. For more information about supported authentication options, see the OIDC provider client authentication section in the Quarkus "OpenID Connect authorization code flow mechanism for protecting web applications" guide.

1.1.16. Testing

Note

If you have to test Quarkus OIDC service endpoints that require Keycloak authorization, follow the Test Keycloak authorization section.

You can begin testing by adding the following dependencies to your test project:

  • Using Maven:

    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.quarkus</groupId>
        <artifactId>quarkus-junit5</artifactId>
        <scope>test</scope>
    </dependency>
    Copy to Clipboard Toggle word wrap
  • Using Gradle:

    testImplementation("io.rest-assured:rest-assured")
    testImplementation("io.quarkus:quarkus-junit5")
    Copy to Clipboard Toggle word wrap
1.1.16.1. Dev Services for Keycloak

The preferred approach for integration testing against Keycloak is Dev Services for Keycloak. Dev Services for Keycloak will start and initialize a test container. Then, it will create a quarkus realm and a quarkus-app client (secret secret) and add alice (admin and user roles) and bob (user role) users, where all of these properties can be customized.

First, add the following dependency, which provides a utility class io.quarkus.test.keycloak.client.KeycloakTestClient that you can use in tests for acquiring the access tokens:

  • Using Maven:

    <dependency>
        <groupId>io.quarkus</groupId>
        <artifactId>quarkus-test-keycloak-server</artifactId>
        <scope>test</scope>
    </dependency>
    Copy to Clipboard Toggle word wrap
  • Using Gradle:

    testImplementation("io.quarkus:quarkus-test-keycloak-server")
    Copy to Clipboard Toggle word wrap

Next, prepare your application.properties configuration file. You can start with an empty application.properties file because Dev Services for Keycloak registers quarkus.oidc.auth-server-url and points it to the running test container, quarkus.oidc.client-id=quarkus-app, and quarkus.oidc.credentials.secret=secret.

However, if you have already configured the required quarkus-oidc properties, then you only need to associate quarkus.oidc.auth-server-url with the prod profile for `Dev Services for Keycloak`to start a container, as shown in the following example:

%prod.quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
Copy to Clipboard Toggle word wrap

If a custom realm file has to be imported into Keycloak before running the tests, configure Dev Services for Keycloak as follows:

%prod.quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.keycloak.devservices.realm-path=quarkus-realm.json
Copy to Clipboard Toggle word wrap

Finally, write your test, which will be executed in JVM mode, as shown in the following examples:

Example of a test executed in JVM mode:

package org.acme.security.openid.connect;

import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.keycloak.client.KeycloakTestClient;
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;

@QuarkusTest
public class BearerTokenAuthenticationTest {

    KeycloakTestClient keycloakClient = new KeycloakTestClient();

    @Test
    public void testAdminAccess() {
        RestAssured.given().auth().oauth2(getAccessToken("alice"))
                .when().get("/api/admin")
                .then()
                .statusCode(200);
        RestAssured.given().auth().oauth2(getAccessToken("bob"))
                .when().get("/api/admin")
                .then()
                .statusCode(403);
    }

    protected String getAccessToken(String userName) {
        return keycloakClient.getAccessToken(userName);
    }
}
Copy to Clipboard Toggle word wrap

Example of a test executed in native mode:

package org.acme.security.openid.connect;

import io.quarkus.test.junit.QuarkusIntegrationTest;

@QuarkusIntegrationTest
public class NativeBearerTokenAuthenticationIT extends BearerTokenAuthenticationTest {
}
Copy to Clipboard Toggle word wrap

For more information about initializing and configuring Dev Services for Keycloak, see the Dev Services for Keycloak guide.

1.1.16.2. WireMock

Add the following dependencies to your test project:

  • Using Maven:

    <dependency>
        <groupId>io.quarkus</groupId>
        <artifactId>quarkus-test-oidc-server</artifactId>
        <scope>test</scope>
    </dependency>
    Copy to Clipboard Toggle word wrap
  • Using Gradle:

    testImplementation("io.quarkus:quarkus-test-oidc-server")
    Copy to Clipboard Toggle word wrap

Prepare the REST test endpoint and set application.properties. For example:

# keycloak.url is set by OidcWiremockTestResource
quarkus.oidc.auth-server-url=${keycloak.url:replaced-by-test-resource}/realms/quarkus/
quarkus.oidc.client-id=quarkus-service-app
quarkus.oidc.application-type=service
Copy to Clipboard Toggle word wrap

Finally, write the test code. For example:

import static org.hamcrest.Matchers.equalTo;

import java.util.Set;

import org.junit.jupiter.api.Test;

import io.quarkus.test.common.QuarkusTestResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.oidc.server.OidcWiremockTestResource;
import io.restassured.RestAssured;
import io.smallrye.jwt.build.Jwt;

@QuarkusTest
@QuarkusTestResource(OidcWiremockTestResource.class)
public class BearerTokenAuthorizationTest {

    @Test
    public void testBearerToken() {
        RestAssured.given().auth().oauth2(getAccessToken("alice", Set.of("user")))
            .when().get("/api/users/me")
            .then()
            .statusCode(200)
            // The test endpoint returns the name extracted from the injected `SecurityIdentity` principal.
            .body("userName", equalTo("alice"));
    }

    private String getAccessToken(String userName, Set<String> groups) {
        return Jwt.preferredUserName(userName)
                .groups(groups)
                .issuer("https://server.example.com")
                .audience("https://service.example.com")
                .sign();
    }
}
Copy to Clipboard Toggle word wrap

The quarkus-test-oidc-server extension includes a signing RSA private key file in a JSON Web Key (JWK) format and points to it with a smallrye.jwt.sign.key.location configuration property. It allows you to sign the token by using a no-argument sign() operation.

Testing your quarkus-oidc service application with OidcWiremockTestResource provides the best coverage because even the communication channel is tested against the WireMock HTTP stubs. If you need to run a test with WireMock stubs that are not yet supported by OidcWiremockTestResource, you can inject a WireMockServer instance into the test class, as shown in the following example:

Note

OidcWiremockTestResource does not work with @QuarkusIntegrationTest against Docker containers because the WireMock server runs in the JVM that runs the test, which is inaccessible from the Docker container that runs the Quarkus application.

package io.quarkus.it.keycloak;

import static com.github.tomakehurst.wiremock.client.WireMock.matching;
import static org.hamcrest.Matchers.equalTo;

import org.junit.jupiter.api.Test;

import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;

import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.oidc.server.OidcWireMock;
import io.restassured.RestAssured;

@QuarkusTest
public class CustomOidcWireMockStubTest {

    @OidcWireMock
    WireMockServer wireMockServer;

    @Test
    public void testInvalidBearerToken() {
        wireMockServer.stubFor(WireMock.post("/auth/realms/quarkus/protocol/openid-connect/token/introspect")
                .withRequestBody(matching(".*token=invalid_token.*"))
                .willReturn(WireMock.aResponse().withStatus(400)));

        RestAssured.given().auth().oauth2("invalid_token").when()
                .get("/api/users/me/bearer")
                .then()
                .statusCode(401)
                .header("WWW-Authenticate", equalTo("Bearer"));
    }
}
Copy to Clipboard Toggle word wrap
1.1.16.3. OidcTestClient

If you use SaaS OIDC providers, such as Auth0, and want to run tests against the test (development) domain or to run tests against a remote Keycloak test realm, if you already have quarkus.oidc.auth-server-url configured, you can use OidcTestClient.

For example, you have the following configuration:

%test.quarkus.oidc.auth-server-url=https://dev-123456.eu.auth0.com/
%test.quarkus.oidc.client-id=test-auth0-client
%test.quarkus.oidc.credentials.secret=secret
Copy to Clipboard Toggle word wrap

To start, add the same dependency, quarkus-test-oidc-server, as described in the WireMock section.

Next, write the test code as follows:

package org.acme;

import org.junit.jupiter.api.AfterAll;
import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.is;

import java.util.Map;

import org.junit.jupiter.api.Test;

import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.oidc.client.OidcTestClient;

@QuarkusTest
public class GreetingResourceTest {

    static OidcTestClient oidcTestClient = new OidcTestClient();

    @AfterAll
    public static void close() {
        oidcTestClient.close();
    }

    @Test
    public void testHelloEndpoint() {
        given()
          .auth().oauth2(getAccessToken("alice", "alice"))
          .when().get("/hello")
          .then()
             .statusCode(200)
             .body(is("Hello, Alice"));
    }

    private String getAccessToken(String name, String secret) {
        return oidcTestClient.getAccessToken(name, secret,
            Map.of("audience", "https://dev-123456.eu.auth0.com/api/v2/",
	           "scope", "profile"));
    }
}
Copy to Clipboard Toggle word wrap

This test code acquires a token by using a password grant from the test Auth0 domain, which has registered an application with the client id test-auth0-client, and created the user alice with password alice. For a test like this to work, the test Auth0 application must have the password grant enabled. This example code also shows how to pass additional parameters. For Auth0, these are the audience and scope parameters.

1.1.16.3.1. Test OIDC DevService

You can also use OidcTestClient to test Quarkus endpoints supported by Dev Services for OIDC. No configuration in the application.properties file is needed, Quarkus will configure OidcTestClient for you:

package org.acme;

import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.is;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;

import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.oidc.client.OidcTestClient;

@QuarkusTest
public class GreetingResourceTest {

    static final OidcTestClient oidcTestClient = new OidcTestClient();

    @AfterAll
    public static void close() {
        oidcTestClient.close();
    }

    @Test
    public void testHelloEndpoint() {
        String accessToken = oidcTestClient.getAccessToken("alice", "alice");
        given()
          .auth().oauth2(accessToken)
          .when().get("/hello")
          .then()
             .statusCode(200)
             .body(is("Hello, Alice"));
    }

}
Copy to Clipboard Toggle word wrap
1.1.16.4. Local public key

You can use a local inlined public key for testing your quarkus-oidc service applications, as shown in the following example:

quarkus.oidc.client-id=test
quarkus.oidc.public-key=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlivFI8qB4D0y2jy0CfEqFyy46R0o7S8TKpsx5xbHKoU1VWg6QkQm+ntyIv1p4kE1sPEQO73+HY8+Bzs75XwRTYL1BmR1w8J5hmjVWjc6R2BTBGAYRPFRhor3kpM6ni2SPmNNhurEAHw7TaqszP5eUF/F9+KEBWkwVta+PZ37bwqSE4sCb1soZFrVz/UT/LF4tYpuVYt3YbqToZ3pZOZ9AX2o1GCG3xwOjkc4x0W7ezbQZdC9iftPxVHR8irOijJRRjcPDtA6vPKpzLl6CyYnsIYPd99ltwxTHjr3npfv/3Lw50bAkbT4HeLFxTx4flEoZLKO/g0bAoV2uqBhkA9xnQIDAQAB

smallrye.jwt.sign.key.location=/privateKey.pem
Copy to Clipboard Toggle word wrap

To generate JWT tokens, copy privateKey.pem from the integration-tests/oidc-tenancy in the main Quarkus repository and use a test code similar to the one in the preceding WireMock section. You can use your own test keys, if preferred.

This approach provides limited coverage compared to the WireMock approach. For example, the remote communication code is not covered.

1.1.16.5. TestSecurity annotation

You can use @TestSecurity and @OidcSecurity annotations to test the service application endpoint code, which depends on either one, or all three, of the following injections:

  • JsonWebToken
  • UserInfo
  • OidcConfigurationMetadata

First, add the following dependency:

  • Using Maven:

    <dependency>
        <groupId>io.quarkus</groupId>
        <artifactId>quarkus-test-security-oidc</artifactId>
        <scope>test</scope>
    </dependency>
    Copy to Clipboard Toggle word wrap
  • Using Gradle:

    testImplementation("io.quarkus:quarkus-test-security-oidc")
    Copy to Clipboard Toggle word wrap

Write a test code as outlined in the following example:

import static org.hamcrest.Matchers.is;
import org.junit.jupiter.api.Test;
import io.quarkus.test.common.http.TestHTTPEndpoint;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.security.TestSecurity;
import io.quarkus.test.security.oidc.Claim;
import io.quarkus.test.security.oidc.ConfigMetadata;
import io.quarkus.test.security.oidc.OidcSecurity;
import io.quarkus.test.security.oidc.UserInfo;
import io.restassured.RestAssured;

@QuarkusTest
@TestHTTPEndpoint(ProtectedResource.class)
public class TestSecurityAuthTest {

    @Test
    @TestSecurity(user = "userOidc", roles = "viewer")
    public void testOidc() {
        RestAssured.when().get("test-security-oidc").then()
                .body(is("userOidc:viewer"));
    }

    @Test
    @TestSecurity(user = "userOidc", roles = "viewer")
    @OidcSecurity(claims = {
            @Claim(key = "email", value = "user@gmail.com")
    }, userinfo = {
            @UserInfo(key = "sub", value = "subject")
    }, config = {
            @ConfigMetadata(key = "issuer", value = "issuer")
    })
    public void testOidcWithClaimsUserInfoAndMetadata() {
        RestAssured.when().get("test-security-oidc-claims-userinfo-metadata").then()
                .body(is("userOidc:viewer:user@gmail.com:subject:issuer"));
    }

}
Copy to Clipboard Toggle word wrap

The ProtectedResource class, which is used in this code example, might look like this:

import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;

import io.quarkus.oidc.OidcConfigurationMetadata;
import io.quarkus.oidc.UserInfo;
import io.quarkus.security.Authenticated;

import org.eclipse.microprofile.jwt.JsonWebToken;

@Path("/service")
@Authenticated
public class ProtectedResource {

    @Inject
    JsonWebToken accessToken;
    @Inject
    UserInfo userInfo;
    @Inject
    OidcConfigurationMetadata configMetadata;

    @GET
    @Path("test-security-oidc")
    public String testSecurityOidc() {
        return accessToken.getName() + ":" + accessToken.getGroups().iterator().next();
    }

    @GET
    @Path("test-security-oidc-claims-userinfo-metadata")
    public String testSecurityOidcWithClaimsUserInfoMetadata() {
        return accessToken.getName() + ":" + accessToken.getGroups().iterator().next()
                + ":" + accessToken.getClaim("email")
                + ":" + userInfo.getString("sub")
                + ":" + configMetadata.get("issuer");
    }
}
Copy to Clipboard Toggle word wrap

You must always use the @TestSecurity annotation. Its user property is returned as JsonWebToken.getName() and its roles property is returned as JsonWebToken.getGroups(). The @OidcSecurity annotation is optional and you can use it to set the additional token claims and the UserInfo and OidcConfigurationMetadata properties. Additionally, if the quarkus.oidc.token.issuer property is configured, it is used as an OidcConfigurationMetadata issuer property value.

If you work with opaque tokens, you can test them as shown in the following code example:

import static org.hamcrest.Matchers.is;
import org.junit.jupiter.api.Test;
import io.quarkus.test.common.http.TestHTTPEndpoint;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.security.TestSecurity;
import io.quarkus.test.security.oidc.OidcSecurity;
import io.quarkus.test.security.oidc.TokenIntrospection;
import io.restassured.RestAssured;

@QuarkusTest
@TestHTTPEndpoint(ProtectedResource.class)
public class TestSecurityAuthTest {

    @Test
    @TestSecurity(user = "userOidc", roles = "viewer")
    @OidcSecurity(introspectionRequired = true,
        introspection = {
            @TokenIntrospection(key = "email", value = "user@gmail.com")
        }
    )
    public void testOidcWithClaimsUserInfoAndMetadata() {
        RestAssured.when().get("test-security-oidc-opaque-token").then()
                .body(is("userOidc:viewer:userOidc:viewer:user@gmail.com"));
    }

}
Copy to Clipboard Toggle word wrap

The ProtectedResource class, which is used in this code example, might look like this:

import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;

import io.quarkus.oidc.TokenIntrospection;
import io.quarkus.security.Authenticated;
import io.quarkus.security.identity.SecurityIdentity;

@Path("/service")
@Authenticated
public class ProtectedResource {

    @Inject
    SecurityIdentity securityIdentity;
    @Inject
    TokenIntrospection introspection;

    @GET
    @Path("test-security-oidc-opaque-token")
    public String testSecurityOidcOpaqueToken() {
        return securityIdentity.getPrincipal().getName() + ":" + securityIdentity.getRoles().iterator().next()
            + ":" + introspection.getString("username")
            + ":" + introspection.getString("scope")
            + ":" + introspection.getString("email");
    }
}
Copy to Clipboard Toggle word wrap

The @TestSecurity, user, and roles attributes are available as TokenIntrospection, username, and scope properties. Use io.quarkus.test.security.oidc.TokenIntrospection to add the additional introspection response properties, such as an email, and so on.

Tip

@TestSecurity and @OidcSecurity can be combined in a meta-annotation, as outlined in the following example:

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.METHOD })
    @TestSecurity(user = "userOidc", roles = "viewer")
    @OidcSecurity(introspectionRequired = true,
        introspection = {
            @TokenIntrospection(key = "email", value = "user@gmail.com")
        }
    )
    public @interface TestSecurityMetaAnnotation {

    }
Copy to Clipboard Toggle word wrap

This is particularly useful if multiple test methods must use the same set of security settings.

1.1.17. Check errors in the logs

To see more details about token verification errors, enable io.quarkus.oidc.runtime.OidcProvider and TRACE level logging:

quarkus.log.category."io.quarkus.oidc.runtime.OidcProvider".level=TRACE
quarkus.log.category."io.quarkus.oidc.runtime.OidcProvider".min-level=TRACE
Copy to Clipboard Toggle word wrap

To see more details about OidcProvider client initialization errors, enable io.quarkus.oidc.runtime.OidcRecorder and TRACE level logging as follows:

quarkus.log.category."io.quarkus.oidc.runtime.OidcRecorder".level=TRACE
quarkus.log.category."io.quarkus.oidc.runtime.OidcRecorder".min-level=TRACE
Copy to Clipboard Toggle word wrap

The externally-accessible token of the OIDC provider and other endpoints might have different HTTP(S) URLs compared to the URLs that are auto-discovered or configured relative to the quarkus.oidc.auth-server-url internal URL. For example, suppose your SPA acquires a token from an external token endpoint address and sends it to Quarkus as a bearer token. In that case, the endpoint might report an issuer verification failure.

In such cases, if you work with Keycloak, start it with the KEYCLOAK_FRONTEND_URL system property set to the externally accessible base URL. If you work with other OIDC providers, refer to your provider’s documentation.

1.1.19. Using the client-id property

The quarkus.oidc.client-id property identifies the OIDC client that requested the current bearer token. The OIDC client can be an SPA application running in a browser or a Quarkus web-app confidential client application propagating the access token to the Quarkus service application.

This property is required if the service application is expected to introspect the tokens remotely, which is always the case for the opaque tokens. This property is optional for local JSON Web Token (JWT) verification only.

Setting the quarkus.oidc.client-id property is encouraged even if the endpoint does not require access to the remote introspection endpoint. This is because when client-id is set, it can be used to verify the token audience. It will also be included in logs when the token verification fails, enabling better traceability of tokens issued to specific clients and analysis over a longer period.

For example, if your OIDC provider sets a token audience, consider the following configuration pattern:

# Set client-id
quarkus.oidc.client-id=quarkus-app
# Token audience claim must contain 'quarkus-app'
quarkus.oidc.token.audience=${quarkus.oidc.client-id}
Copy to Clipboard Toggle word wrap

If you set quarkus.oidc.client-id, but your endpoint does not require remote access to one of the OIDC provider endpoints (introspection, token acquisition, and so on), do not set a client secret with quarkus.oidc.credentials or similar properties because it will not be used.

Note

Quarkus web-app applications always require the quarkus.oidc.client-id property.

1.2. Sender-constraining access tokens

1.2.1. Demonstrating Proof of Possession (DPoP)

RFC9449 describes a Demonstrating Proof of Possession (DPoP) mechanism for cryprographically binding an access token to the current client, preventing the access token loss and replay.

Single page application (SPA) public clients generate DPoP proof tokens and use them to acquire and submit access tokens which are cryptograhically bound to DPoP proofs.

Enabling DPoP support in Quarkus requires a single property.

For example:

quarkus.oidc.auth-server-url=${your_oidc_provider_url}
quarkus.oidc.token.authorization-scheme=dpop 
1
Copy to Clipboard Toggle word wrap
1
Require that the access tokens are provided using HTTP Authorization DPoP scheme value.

After accepting such tokens, Quarkus will go through the full DPoP token verification process.

Support for custom DPoP nonce providers may be offered in the future.

1.2.2. Mutual TLS token binding

RFC8705 describes a mechanism for binding access tokens to Mutual TLS (mTLS) client authentication certificates. It requires that a client certificate’s SHA256 thumbprint matches a JWT token or token introspection confirmation x5t#S256 certificate thumbprint.

For example, see JWT Certificate Thumbprint Confirmation Method and Confirmation Method for Token Introspection sections of RFC8705.

MTLS token binding supports a holder of key concept, and can be used to confirm that the current access token was issued to the current authenticated client who presents this token.

When you use both mTLS and OIDC bearer authentication mechanisms, you can enforce that the access tokens must be certificate bound with a single property, after configuring your Quarkus endpoint and Quarkus OIDC to require the use of mTLS.

For example:

quarkus.oidc.auth-server-url=${your_oidc_provider_url}
quarkus.oidc.token.binding.certificate=true 
1

quarkus.oidc.tls.tls-configuration-name=oidc-client-tls 
2


quarkus.tls.oidc-client-tls.key-store.p12.path=target/certificates/oidc-client-keystore.p12 
3

quarkus.tls.oidc-client-tls.key-store.p12.password=password
quarkus.tls.oidc-client-tls.trust-store.p12.path=target/certificates/oidc-client-truststore.p12
quarkus.tls.oidc-client-tls.trust-store.p12.password=password

quarkus.http.tls-configuration-name=oidc-server-mtls 
4

quarkus.tls.oidc-server-mtls.key-store.p12.path=target/certificates/oidc-keystore.p12
quarkus.tls.oidc-server-mtls.key-store.p12.password=password
quarkus.tls.oidc-server-mtls.trust-store.p12.path=target/certificates/oidc-server-truststore.p12
quarkus.tls.oidc-server-mtls.trust-store.p12.password=password
Copy to Clipboard Toggle word wrap
1
Require that bearer access tokens must be bound to the client certificates.
2 3
TLS registry configuration for Quarkus OIDC be able to communicate with the OIDC provider over MTLS
4
TLS registry configuration requiring external clients to authenticate to the Quarkus endpoint over MTLS

The above configuration is sufficient to require that OIDC bearer tokens are bound to the client certificates.

Next, if you need to access both mTLS and OIDC bearer security identities, consider enabling Inclusive authentication with quarkus.http.auth.inclusive=true.

Now you can access both MTLS and OIDC security identities as follows:

package io.quarkus.it.oidc;

import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;

import org.eclipse.microprofile.jwt.JsonWebToken;
import io.quarkus.security.Authenticated;
import io.quarkus.security.credential.CertificateCredential;
import io.quarkus.security.identity.SecurityIdentity;

@Path("/service")
@Authenticated
public class OidcMtlsEndpoint {

    @Inject
    SecurityIdentity mtlsIdentity; 
1


    @Inject
    JsonWebToken oidcAccessToken; 
2


    @GET
    public String getIdentities() {
        var cred = identity.getCredential(CertificateCredential.class).getCertificate();
        return "Identities: " + cred.getSubjectX500Principal().getName().split(",")[0]
                + ", " + accessToken.getName();
    }
}
Copy to Clipboard Toggle word wrap
1
SecurityIdentity always represents the primary mTLS authentication when mTLS is used and an inclusive authentication is enabled.
2
OIDC security identity is also available because enabling an inclusive authentication requires all registered mechanisms to produce the security identity.

Sometimes, SecurityIdentity for a given token must be created when there is no active HTTP request context. The quarkus-oidc extension provides io.quarkus.oidc.TenantIdentityProvider to convert a token to a SecurityIdentity instance. For example, one situation when you must verify the token after the HTTP request has completed is when you are processing messages with Vert.x event bus. The example below uses the 'product-order' message within different CDI request contexts. Therefore, an injected SecurityIdentity would not correctly represent the verified identity and be anonymous.

package org.acme.quickstart.oidc;

import static jakarta.ws.rs.core.HttpHeaders.AUTHORIZATION;

import jakarta.inject.Inject;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import io.vertx.core.eventbus.EventBus;

@Path("order")
public class OrderResource {

    @Inject
    EventBus eventBus;

    @POST
    public void order(String product, @HeaderParam(AUTHORIZATION) String bearer) {
        String rawToken = bearer.substring("Bearer ".length()); 
1

        eventBus.publish("product-order", new Product(product, rawToken));
    }

    public static class Product {
         public String product;
         public String customerAccessToken;
         public Product() {
         }
         public Product(String product, String customerAccessToken) {
             this.product = product;
             this.customerAccessToken = customerAccessToken;
         }
    }
}
Copy to Clipboard Toggle word wrap
1
At this point, the token is not verified when proactive authentication is disabled.
package org.acme.quickstart.oidc;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;

import io.quarkus.oidc.AccessTokenCredential;
import io.quarkus.oidc.Tenant;
import io.quarkus.oidc.TenantIdentityProvider;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.vertx.ConsumeEvent;
import io.smallrye.common.annotation.Blocking;

@ApplicationScoped
public class OrderService {

    @Tenant("tenantId")
    @Inject
    TenantIdentityProvider identityProvider;

    @Inject
    TenantIdentityProvider defaultIdentityProvider; 
1


    @Blocking
    @ConsumeEvent("product-order")
    void processOrder(OrderResource.Product product) {
        AccessTokenCredential tokenCredential = new AccessTokenCredential(product.customerAccessToken);
        SecurityIdentity securityIdentity = identityProvider.authenticate(tokenCredential).await().indefinitely(); 
2

        ...
    }

}
Copy to Clipboard Toggle word wrap
1
For the default tenant, the Tenant qualifier is optional.
2
Executes token verification and converts the token to a SecurityIdentity.
Note

When the provider is used during an HTTP request, the tenant configuration can be resolved as described in the Using OpenID Connect Multi-Tenancy guide. However, when there is no active HTTP request, you must select the tenant explicitly with the io.quarkus.oidc.Tenant qualifier.

Warning

Dynamic tenant configuration resolution is currently not supported. Authentication that requires a dynamic tenant will fail.

1.4. OIDC request filters

You can filter OIDC requests made by Quarkus to the OIDC provider by registering one or more OidcRequestFilter implementations, which can update or add new request headers, and log requests. For more information, see OIDC request filters.

1.4.1. OIDC response filters

You can filter responses from the OIDC providers by registering one or more OidcResponseFilter implementations, which can check the response status, headers and body in order to log them or perform other actions.

You can have a single filter intercepting all the OIDC responses, or use an @OidcEndpoint annotation to apply this filter to the specific endpoint responses only. For example:

package io.quarkus.it.keycloak;

import jakarta.enterprise.context.ApplicationScoped;

import io.quarkus.arc.Unremovable;
import io.quarkus.logging.Log;
import io.quarkus.oidc.common.OidcEndpoint;
import io.quarkus.oidc.common.OidcEndpoint.Type;
import io.quarkus.oidc.common.OidcResponseFilter;
import io.quarkus.oidc.common.runtime.OidcConstants;
import io.quarkus.oidc.runtime.OidcUtils;

@ApplicationScoped
@Unremovable
@OidcEndpoint(value = Type.DISCOVERY) 
1

public class DiscoveryEndpointResponseFilter implements OidcResponseFilter {

    @Override
    public void filter(OidcResponseContext rc) {
        String contentType = rc.responseHeaders().get("Content-Type"); 
2

        if (contentType.equals("application/json") {
            String tenantId = rc.requestProperties().get(OidcUtils.TENANT_ID_ATTRIBUTE); 
3

            String metadata = rc.responseBody().toString(); 
4

            Log.debugf("Tenant %s OIDC metadata: %s", tenantId, metadata);
        }
    }
}
Copy to Clipboard Toggle word wrap
1
Restrict this filter to requests targeting the OIDC discovery endpoint only.
2
Check the response Content-Type header.
3
Use OidcRequestContextProperties request properties to get the tenant id.
4
Get the response data as String.

1.5. Programmatic OIDC start-up

OIDC tenants can be created programmatically like in the example below:

package io.quarkus.it.oidc;

import io.quarkus.oidc.Oidc;
import jakarta.enterprise.event.Observes;

public class OidcStartup {

    void observe(@Observes Oidc oidc) {
        oidc.createServiceApp("http://localhost:8180/realms/quarkus");
    }

}
Copy to Clipboard Toggle word wrap

The code above is a programmatic equivalent to the following configuration in the application.properties file:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
Copy to Clipboard Toggle word wrap

Should you need to configure more OIDC tenant properties, use the OidcTenantConfig builder like in the example below:

package io.quarkus.it.oidc;

import io.quarkus.oidc.Oidc;
import io.quarkus.oidc.OidcTenantConfig;
import jakarta.enterprise.event.Observes;

public class OidcStartup {

    void createDefaultTenant(@Observes Oidc oidc) {
        var defaultTenant = OidcTenantConfig
                .authServerUrl("http://localhost:8180/realms/quarkus")
                .token().requireJwtIntrospectionOnly().end()
                .build();
        oidc.create(defaultTenant);
    }
}
Copy to Clipboard Toggle word wrap

For more complex setup involving multiple tenants please see the Programmatic OIDC start-up for multitenant application section of the OpenID Connect Multi-Tenancy guide.

1.6. References

Use the Quarkus OpenID Connect (OIDC) extension to secure a Jakarta REST application with Bearer token authentication. The bearer tokens are issued by OIDC and OAuth 2.0 compliant authorization servers, such as Keycloak.

For more information about OIDC Bearer token authentication, see the Quarkus OpenID Connect (OIDC) Bearer token authentication guide.

If you want to protect web applications by using OIDC Authorization Code Flow authentication, see the OpenID Connect authorization code flow mechanism for protecting web applications guide.

2.1. Prerequisites

To complete this guide, you need:

  • Roughly 15 minutes
  • An IDE
  • JDK 17+ installed with JAVA_HOME configured appropriately
  • Apache Maven 3.8.6 or later
  • A working container runtime (Docker or Podman)
  • Optionally the Quarkus CLI if you want to use it
  • Optionally Mandrel or GraalVM installed and configured appropriately if you want to build a native executable (or Docker if you use a native container build)
  • The jq command-line processor tool

2.2. Architecture

This example shows how you can build a simple microservice that offers two endpoints:

  • /api/users/me
  • /api/admin

These endpoints are protected and can only be accessed if a client sends a bearer token along with the request, which must be valid (for example, signature, expiration, and audience) and trusted by the microservice.

A Keycloak server issues the bearer token and represents the subject for which the token was issued. Because it is an OAuth 2.0 authorization server, the token also references the client acting on the user’s behalf.

Any user with a valid token can access the /api/users/me endpoint. As a response, it returns a JSON document with user details obtained from the information in the token.

The /api/admin endpoint is protected with RBAC (Role-Based Access Control), which only users with the admin role can access. At this endpoint, the @RolesAllowed annotation is used to enforce the access constraint declaratively.

2.3. Solution

Follow the instructions in the next sections and create the application step by step. You can also go straight to the completed example.

You can clone the Git repository by running the command git clone https://github.com/quarkusio/quarkus-quickstarts.git -b 3.20, or you can download an archive.

The solution is located in the security-openid-connect-quickstart directory.

2.4. Create the Maven project

You can either create a new Maven project with the oidc extension or you can add the extension to an existing Maven project. Complete one of the following commands:

To create a new Maven project, use the following command:

  • Using the Quarkus CLI:

    quarkus create app org.acme:security-openid-connect-quickstart \
        --extension='oidc,rest-jackson' \
        --no-code
    cd security-openid-connect-quickstart
    Copy to Clipboard Toggle word wrap

    To create a Gradle project, add the --gradle or --gradle-kotlin-dsl option.

    For more information about how to install and use the Quarkus CLI, see the Quarkus CLI guide.

  • Using Maven:

    mvn com.redhat.quarkus.platform:quarkus-maven-plugin:3.20.1:create \
        -DprojectGroupId=org.acme \
        -DprojectArtifactId=security-openid-connect-quickstart \
        -Dextensions='oidc,rest-jackson' \
        -DnoCode
    cd security-openid-connect-quickstart
    Copy to Clipboard Toggle word wrap

    To create a Gradle project, add the -DbuildTool=gradle or -DbuildTool=gradle-kotlin-dsl option.

For Windows users:

  • If using cmd, (don’t use backward slash \ and put everything on the same line)
  • If using Powershell, wrap -D parameters in double quotes e.g. "-DprojectArtifactId=security-openid-connect-quickstart"

If you already have your Quarkus project configured, you can add the oidc extension to your project by running the following command in your project base directory:

  • Using the Quarkus CLI:

    quarkus extension add oidc
    Copy to Clipboard Toggle word wrap
  • Using Maven:

    ./mvnw quarkus:add-extension -Dextensions='oidc'
    Copy to Clipboard Toggle word wrap
  • Using Gradle:

    ./gradlew addExtension --extensions='oidc'
    Copy to Clipboard Toggle word wrap

This will add the following to your build file:

  • Using Maven:

    <dependency>
       <groupId>io.quarkus</groupId>
       <artifactId>quarkus-oidc</artifactId>
    </dependency>
    Copy to Clipboard Toggle word wrap
  • Using Gradle:

    implementation("io.quarkus:quarkus-oidc")
    Copy to Clipboard Toggle word wrap

2.5. Write the application

  1. Implement the /api/users/me endpoint as shown in the following example, which is a regular Jakarta REST resource:

    package org.acme.security.openid.connect;
    
    import jakarta.annotation.security.RolesAllowed;
    import jakarta.inject.Inject;
    import jakarta.ws.rs.GET;
    import jakarta.ws.rs.Path;
    
    import org.jboss.resteasy.reactive.NoCache;
    import io.quarkus.security.identity.SecurityIdentity;
    
    @Path("/api/users")
    public class UsersResource {
    
        @Inject
        SecurityIdentity securityIdentity;
    
        @GET
        @Path("/me")
        @RolesAllowed("user")
        @NoCache
        public User me() {
            return new User(securityIdentity);
        }
    
        public static class User {
    
            private final String userName;
    
            User(SecurityIdentity securityIdentity) {
                this.userName = securityIdentity.getPrincipal().getName();
            }
    
            public String getUserName() {
                return userName;
            }
        }
    }
    Copy to Clipboard Toggle word wrap
  2. Implement the /api/admin endpoint as shown in the following example:

    package org.acme.security.openid.connect;
    
    import jakarta.annotation.security.RolesAllowed;
    import jakarta.ws.rs.GET;
    import jakarta.ws.rs.Path;
    import jakarta.ws.rs.Produces;
    import jakarta.ws.rs.core.MediaType;
    
    @Path("/api/admin")
    public class AdminResource {
    
        @GET
        @RolesAllowed("admin")
        @Produces(MediaType.TEXT_PLAIN)
        public String admin() {
            return "granted";
        }
    }
    Copy to Clipboard Toggle word wrap
    Note

    The main difference in this example is that the @RolesAllowed annotation is used to verify that only users granted the admin role can access the endpoint.

Injection of the SecurityIdentity is supported in both @RequestScoped and @ApplicationScoped contexts.

2.6. Configure the application

  • Configure the Quarkus OpenID Connect (OIDC) extension by setting the following configuration properties in the src/main/resources/application.properties file.

    %prod.quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
    quarkus.oidc.client-id=backend-service
    quarkus.oidc.credentials.secret=secret
    
    # Tell Dev Services for Keycloak to import the realm file
    # This property is not effective when running the application in JVM or native modes
    
    quarkus.keycloak.devservices.realm-path=quarkus-realm.json
    Copy to Clipboard Toggle word wrap

Where:

  • %prod.quarkus.oidc.auth-server-url sets the base URL of the OpenID Connect (OIDC) server. The %prod. profile prefix ensures that Dev Services for Keycloak launches a container when you run the application in development (dev) mode. For more information, see the Run the application in dev mode section.
  • quarkus.oidc.client-id sets a client id that identifies the application.
  • quarkus.oidc.credentials.secret sets the client secret, which is used by the client_secret_basic authentication method.

For more information, see the Quarkus OpenID Connect (OIDC) configuration properties guide.

2.7. Start and configure the Keycloak server

  1. Put the realm configuration file on the classpath (target/classes directory) so that it gets imported automatically when running in dev mode. You do not need to do this if you have already built a complete solution, in which case, this realm file is added to the classpath during the build.

    Note

    Do not start the Keycloak server when you run the application in dev mode; Dev Services for Keycloak will start a container. For more information, see the Run the application in dev mode section.

  2. To start a Keycloak server, you can use Docker to run the following command:

    docker run --name keycloak -e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin -p 8180:8080 quay.io/keycloak/keycloak:{keycloak.version} start-dev
    Copy to Clipboard Toggle word wrap
    • Where the keycloak.version is set to version 26.1.3 or later.
  3. You can access your Keycloak server at localhost:8180.
  4. To access the Keycloak Administration console, log in as the admin user by using the following login credentials:

    • Username: admin
    • Password: admin
  5. Import the realm configuration file from the upstream community repository to create a new realm.

For more information, see the Keycloak documentation about creating and configuring a new realm.

2.8. Run the application in dev mode

  1. To run the application in dev mode, run the following commands:

    • Using the Quarkus CLI:

      quarkus dev
      Copy to Clipboard Toggle word wrap
    • Using Maven:

      ./mvnw quarkus:dev
      Copy to Clipboard Toggle word wrap
    • Using Gradle:

      ./gradlew --console=plain quarkusDev
      Copy to Clipboard Toggle word wrap
  2. Open a Dev UI, which you can find at /q/dev-ui. Then, in an OpenID Connect card, click the Keycloak provider link .
  3. When prompted to log in to a Single Page Application provided by OpenID Connect Dev UI, do the following steps:

    • Log in as alice (password: alice), who has a user role.

      • Accessing /api/admin returns a 403 status code.
      • Accessing /api/users/me returns a 200 status code.
    • Log out and log in again as admin (password: admin), who has both admin and user roles.

      • Accessing /api/admin returns a 200 status code.
      • Accessing /api/users/me returns a 200 status code.

2.9. Run the Application in JVM mode

When you are done with dev mode, you can run the application as a standard Java application.

  1. Compile the application:

    • Using the Quarkus CLI:

      quarkus build
      Copy to Clipboard Toggle word wrap
    • Using Maven:

      ./mvnw install
      Copy to Clipboard Toggle word wrap
    • Using Gradle:

      ./gradlew build
      Copy to Clipboard Toggle word wrap
  2. Run the application:

    java -jar target/quarkus-app/quarkus-run.jar
    Copy to Clipboard Toggle word wrap

2.10. Run the application in native mode

You can compile this same demo as-is into native mode without any modifications. This implies that you no longer need to install a JVM on your production environment. The runtime technology is included in the produced binary and optimized to run with minimal resources required.

Compilation takes a bit longer, so this step is disabled by default.

  1. Build your application again by enabling the native profile:

    • Using the Quarkus CLI:

      quarkus build --native
      Copy to Clipboard Toggle word wrap
    • Using Maven:

      ./mvnw install -Dnative
      Copy to Clipboard Toggle word wrap
    • Using Gradle:

      ./gradlew build -Dquarkus.native.enabled=true
      Copy to Clipboard Toggle word wrap
  2. After waiting a little while, you run the following binary directly:

    ./target/security-openid-connect-quickstart-1.0.0-SNAPSHOT-runner
    Copy to Clipboard Toggle word wrap

2.11. Test the application

For information about testing your application in dev mode, see the preceding Run the application in dev mode section.

You can test the application launched in JVM or native modes with curl.

  • Because the application uses Bearer token authentication, you must first obtain an access token from the Keycloak server to access the application resources:
export access_token=$(\
    curl --insecure -X POST http://localhost:8180/realms/quarkus/protocol/openid-connect/token \
    --user backend-service:secret \
    -H 'content-type: application/x-www-form-urlencoded' \
    -d 'username=alice&password=alice&grant_type=password' | jq --raw-output '.access_token' \
 )
Copy to Clipboard Toggle word wrap
Note

When the quarkus.oidc.authentication.user-info-required property is set to true to require that an access token is used to request UserInfo, you must add a scope=openid query parameter to the token grant request command, for example:

export access_token=$(\
    curl --insecure -X POST http://localhost:8180/realms/quarkus/protocol/openid-connect/token \
    --user backend-service:secret \
    -H 'content-type: application/x-www-form-urlencoded' \
    -d 'username=alice&password=alice&grant_type=password&scope=openid' | jq --raw-output '.access_token' \
 )
Copy to Clipboard Toggle word wrap

The preceding example obtains an access token for the user alice.

curl -v -X GET \
  http://localhost:8080/api/users/me \
  -H "Authorization: Bearer "$access_token
Copy to Clipboard Toggle word wrap
  • Only users with the admin role can access the http://localhost:8080/api/admin endpoint. If you try to access this endpoint with the previously-issued access token, you get a 403 response from the server.
curl -v -X GET \
   http://localhost:8080/api/admin \
   -H "Authorization: Bearer "$access_token
Copy to Clipboard Toggle word wrap
  • To access the admin endpoint, obtain a token for the admin user:
export access_token=$(\
    curl --insecure -X POST http://localhost:8180/realms/quarkus/protocol/openid-connect/token \
    --user backend-service:secret \
    -H 'content-type: application/x-www-form-urlencoded' \
    -d 'username=admin&password=admin&grant_type=password' | jq --raw-output '.access_token' \
 )
Copy to Clipboard Toggle word wrap

For information about writing integration tests that depend on Dev Services for Keycloak, see the Dev Services for Keycloak section of the "OpenID Connect (OIDC) Bearer token authentication" guide.

2.12. References

To protect your web applications, you can use the industry-standard OpenID Connect (OIDC) Authorization Code Flow mechanism provided by the Quarkus OIDC extension.

The Quarkus OpenID Connect (OIDC) extension can protect application HTTP endpoints by using the OIDC Authorization Code Flow mechanism supported by OIDC-compliant authorization servers, such as Keycloak.

The Authorization Code Flow mechanism authenticates users of your web application by redirecting them to an OIDC provider, such as Keycloak, to log in. After authentication, the OIDC provider redirects the user back to the application with an authorization code that confirms that authentication was successful. Then, the application exchanges this code with the OIDC provider for an ID token (which represents the authenticated user), an access token, and a refresh token to authorize the user’s access to the application.

The following diagram outlines the Authorization Code Flow mechanism in Quarkus.

Figure 3.1. Authorization code flow mechanism in Quarkus

  1. The Quarkus user requests access to a Quarkus web-app application.
  2. The Quarkus web-app redirects the user to the authorization endpoint, that is, the OIDC provider for authentication.
  3. The OIDC provider redirects the user to a login and authentication prompt.
  4. At the prompt, the user enters their user credentials.
  5. The OIDC provider authenticates the user credentials entered and, if successful, issues an authorization code and redirects the user back to the Quarkus web-app with the code included as a query parameter.
  6. The Quarkus web-app exchanges this authorization code with the OIDC provider for ID, access, and refresh tokens.

The authorization code flow is completed and the Quarkus web-app uses the tokens issued to access information about the user and grants the relevant role-based authorization to that user. The following tokens are issued:

  • ID token: The Quarkus web-app application uses the user information in the ID token to enable the authenticated user to log in securely and to provide role-based access to the web application.
  • Access token: The Quarkus web-app might use the access token to access the UserInfo API to get additional information about the authenticated user or to propagate it to another endpoint.
  • Refresh token: (Optional) If the ID and access tokens expire, the Quarkus web-app can use the refresh token to get new ID and access tokens.

See also the OIDC configuration properties reference guide.

To learn about how you can protect web applications by using the OIDC Authorization Code Flow mechanism, see Protect a web application by using OIDC authorization code flow.

If you want to protect service applications by using OIDC Bearer token authentication, see OIDC Bearer token authentication.

For information about how to support multiple tenants, see Using OpenID Connect Multi-Tenancy.

3.2. Using the authorization code flow mechanism

To enable an authorization code flow authentication, the quarkus.oidc.application-type property must be set to web-app. Usually, the Quarkus OIDC web-app application type must be set when your Quarkus application is a frontend application which serves HTML pages and requires an OIDC single sign-on login. For the Quarkus OIDC web-app application, the authorization code flow is defined as the preferred method for authenticating users. When your application serves HTML pages and provides REST API at the same time, and requires both the authorization code flow authentication and the bearer access token authentication, the quarkus.oidc.application-type property can be set to hybrid instead. In this case, the authorization code flow is only triggered when an HTTP Authorization request header with a Bearer authorization scheme containing a bearer access token is not set.

The OIDC web-app application requires URLs of the OIDC provider’s authorization, token, JsonWebKey (JWK) set, and possibly the UserInfo, introspection and end-session (RP-initiated logout) endpoints.

By convention, they are discovered by adding a /.well-known/openid-configuration path to the configured quarkus.oidc.auth-server-url.

Alternatively, if the discovery endpoint is not available, or you prefer to reduce the discovery endpoint round-trip, you can disable endpoint discovery and configure relative path values. For example:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.oidc.discovery-enabled=false
# Authorization endpoint: http://localhost:8180/realms/quarkus/protocol/openid-connect/auth
quarkus.oidc.authorization-path=/protocol/openid-connect/auth
# Token endpoint: http://localhost:8180/realms/quarkus/protocol/openid-connect/token
quarkus.oidc.token-path=/protocol/openid-connect/token
# JWK set endpoint: http://localhost:8180/realms/quarkus/protocol/openid-connect/certs
quarkus.oidc.jwks-path=/protocol/openid-connect/certs
# UserInfo endpoint: http://localhost:8180/realms/quarkus/protocol/openid-connect/userinfo
quarkus.oidc.user-info-path=/protocol/openid-connect/userinfo
# Token Introspection endpoint: http://localhost:8180/realms/quarkus/protocol/openid-connect/token/introspect
quarkus.oidc.introspection-path=/protocol/openid-connect/token/introspect
# End-session endpoint: http://localhost:8180/realms/quarkus/protocol/openid-connect/logout
quarkus.oidc.end-session-path=/protocol/openid-connect/logout
Copy to Clipboard Toggle word wrap

Some OIDC providers support metadata discovery but do not return all the endpoint URL values required for the authorization code flow to complete or to support application functions, for example, user logout. To work around this limitation, you can configure the missing endpoint URL values locally, as outlined in the following example:

# Metadata is auto-discovered but it does not return an end-session endpoint URL

quarkus.oidc.auth-server-url=http://localhost:8180/oidcprovider/account

# Configure the end-session URL locally.
# It can be an absolute or relative (to 'quarkus.oidc.auth-server-url') address
quarkus.oidc.end-session-path=logout
Copy to Clipboard Toggle word wrap

You can use this same configuration to override a discovered endpoint URL if that URL does not work for the local Quarkus endpoint and a more specific value is required. For example, a provider that supports both global and application-specific end-session endpoints returns a global end-session URL such as http://localhost:8180/oidcprovider/account/global-logout. This URL will log the user out of all the applications into which the user is currently logged in. However, if the requirement is for the current application to log the user out of a specific application only, you can override the global end-session URL, by setting the quarkus.oidc.end-session-path=logout parameter.

3.2.3. OIDC provider client authentication

OIDC providers typically require applications to be identified and authenticated when they interact with the OIDC endpoints. Quarkus OIDC, specifically the quarkus.oidc.runtime.OidcProviderClient class, authenticates to the OIDC provider when the authorization code must be exchanged for the ID, access, and refresh tokens, or when the ID and access tokens must be refreshed or introspected.

Typically, client id and client secrets are defined for a given application when it enlists to the OIDC provider. All OIDC client authentication options are supported. For example:

Example of client_secret_basic:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus/
quarkus.oidc.client-id=quarkus-app
quarkus.oidc.credentials.secret=mysecret
Copy to Clipboard Toggle word wrap

Or:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus/
quarkus.oidc.client-id=quarkus-app
quarkus.oidc.credentials.client-secret.value=mysecret
Copy to Clipboard Toggle word wrap

The following example shows the secret retrieved from a credentials provider:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus/
quarkus.oidc.client-id=quarkus-app

# This is a key which will be used to retrieve a secret from the map of credentials returned from CredentialsProvider
quarkus.oidc.credentials.client-secret.provider.key=mysecret-key
# This is the keyring provided to the CredentialsProvider when looking up the secret, set only if required by the CredentialsProvider implementation
quarkus.oidc.credentials.client-secret.provider.keyring-name=oidc
# Set it only if more than one CredentialsProvider can be registered
quarkus.oidc.credentials.client-secret.provider.name=oidc-credentials-provider
Copy to Clipboard Toggle word wrap

Example of client_secret_post

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus/
quarkus.oidc.client-id=quarkus-app
quarkus.oidc.credentials.client-secret.value=mysecret
quarkus.oidc.credentials.client-secret.method=post
Copy to Clipboard Toggle word wrap

Example of client_secret_jwt, where the signature algorithm is HS256:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus/
quarkus.oidc.client-id=quarkus-app
quarkus.oidc.credentials.jwt.secret=AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow
Copy to Clipboard Toggle word wrap

Example of client_secret_jwt, where the secret is retrieved from a credentials provider:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus/
quarkus.oidc.client-id=quarkus-app

# This is a key which will be used to retrieve a secret from the map of credentials returned from CredentialsProvider
quarkus.oidc.credentials.jwt.secret-provider.key=mysecret-key
# This is the keyring provided to the CredentialsProvider when looking up the secret, set only if required by the CredentialsProvider implementation
quarkus.oidc.credentials.client-secret.provider.keyring-name=oidc
# Set it only if more than one CredentialsProvider can be registered
quarkus.oidc.credentials.jwt.secret-provider.name=oidc-credentials-provider
Copy to Clipboard Toggle word wrap

Example of private_key_jwt with the PEM key inlined in application.properties, and where the signature algorithm is RS256:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus/
quarkus.oidc.client-id=quarkus-app
quarkus.oidc.credentials.jwt.key=Base64-encoded private key representation
Copy to Clipboard Toggle word wrap

Example of private_key_jwt with the PEM key file, and where the signature algorithm is RS256:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus/
quarkus.oidc.client-id=quarkus-app
quarkus.oidc.credentials.jwt.key-file=privateKey.pem
Copy to Clipboard Toggle word wrap

Example of private_key_jwt with the keystore file, where the signature algorithm is RS256:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus/
quarkus.oidc.client-id=quarkus-app
quarkus.oidc.credentials.jwt.key-store-file=keystore.pkcs12
quarkus.oidc.credentials.jwt.key-store-password=mypassword
quarkus.oidc.credentials.jwt.key-password=mykeypassword

# Private key alias inside the keystore
quarkus.oidc.credentials.jwt.key-id=mykeyAlias
Copy to Clipboard Toggle word wrap

Using client_secret_jwt or private_key_jwt authentication methods ensures that a client secret does not get sent to the OIDC provider, therefore avoiding the risk of a secret being intercepted by a 'man-in-the-middle' attack.

Example how JWT Bearer token can be used to authenticate client

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus/
quarkus.oidc.client-id=quarkus-app
quarkus.oidc.credentials.jwt.source=bearer 
1

quarkus.oidc.credentials.jwt.token-path=/var/run/secrets/tokens 
2
Copy to Clipboard Toggle word wrap

1
Use JWT bearer token to authenticate OIDC provider client, see the Using JWTs for Client Authentication section for more information.
2
Path to a JWT bearer token. Quarkus loads a new token from a filesystem and reloads it when the token has expired.
3.2.3.1. Additional JWT authentication options

If client_secret_jwt, private_key_jwt, or an Apple post_jwt authentication methods are used, then you can customize the JWT signature algorithm, key identifier, audience, subject and issuer. For example:

# private_key_jwt client authentication

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus/
quarkus.oidc.client-id=quarkus-app
quarkus.oidc.credentials.jwt.key-file=privateKey.pem

# This is a token key identifier 'kid' header - set it if your OIDC provider requires it:
# Note if the key is represented in a JSON Web Key (JWK) format with a `kid` property, then
# using 'quarkus.oidc.credentials.jwt.token-key-id' is not necessary.
quarkus.oidc.credentials.jwt.token-key-id=mykey

# Use RS512 signature algorithm instead of the default RS256
quarkus.oidc.credentials.jwt.signature-algorithm=RS512

# The token endpoint URL is the default audience value, use the base address URL instead:
quarkus.oidc.credentials.jwt.audience=${quarkus.oidc-client.auth-server-url}

# custom subject instead of the client id:
quarkus.oidc.credentials.jwt.subject=custom-subject

# custom issuer instead of the client id:
quarkus.oidc.credentials.jwt.issuer=custom-issuer
Copy to Clipboard Toggle word wrap
3.2.3.2. Apple POST JWT

The Apple OIDC provider uses a client_secret_post method whereby a secret is a JWT produced with a private_key_jwt authentication method, but with the Apple account-specific issuer and subject claims.

In Quarkus Security, quarkus-oidc supports a non-standard client_secret_post_jwt authentication method, which you can configure as follows:

# Apple provider configuration sets a 'client_secret_post_jwt' authentication method
quarkus.oidc.provider=apple

quarkus.oidc.client-id=${apple.client-id}
quarkus.oidc.credentials.jwt.key-file=ecPrivateKey.pem
quarkus.oidc.credentials.jwt.token-key-id=${apple.key-id}
# Apple provider configuration sets ES256 signature algorithm

quarkus.oidc.credentials.jwt.subject=${apple.subject}
quarkus.oidc.credentials.jwt.issuer=${apple.issuer}
Copy to Clipboard Toggle word wrap
3.2.3.3. mutual TLS (mTLS)

Some OIDC providers might require that a client is authenticated as part of the mutual TLS authentication process.

The following example shows how you can configure quarkus-oidc to support mTLS:

quarkus.oidc.tls.tls-configuration-name=oidc

# configure hostname verification if necessary
#quarkus.tls.oidc.hostname-verification-algorithm=NONE

# Keystore configuration
quarkus.tls.oidc.key-store.p12.path=client-keystore.p12
quarkus.tls.oidc.key-store.p12.password=${key-store-password}

# Add more keystore properties if needed:
#quarkus.tls.oidc.key-store.p12.alias=keyAlias
#quarkus.tls.oidc.key-store.p12.alias-password=keyAliasPassword

# Truststore configuration
quarkus.tls.oidc.trust-store.p12.path=client-truststore.p12
quarkus.tls.oidc.trust-store.p12.password=${trust-store-password}
# Add more truststore properties if needed:
#quarkus.tls.oidc.trust-store.p12.alias=certAlias
Copy to Clipboard Toggle word wrap
3.2.3.4. POST query

Some providers, such as the Strava OAuth2 provider, require client credentials be posted as HTTP POST query parameters:

quarkus.oidc.provider=strava
quarkus.oidc.client-id=quarkus-app
quarkus.oidc.credentials.client-secret.value=mysecret
quarkus.oidc.credentials.client-secret.method=query
Copy to Clipboard Toggle word wrap
3.2.3.5. Introspection endpoint authentication

Some OIDC providers require authentication to its introspection endpoint by using Basic authentication and with credentials that are different from the client_id and client_secret. If you have previously configured security authentication to support either the client_secret_basic or client_secret_post client authentication methods as described in the OIDC provider client authentication section, you might need to apply the additional configuration as follows.

If the tokens have to be introspected and the introspection endpoint-specific authentication mechanism is required, you can configure quarkus-oidc as follows:

quarkus.oidc.introspection-credentials.name=introspection-user-name
quarkus.oidc.introspection-credentials.secret=introspection-user-secret
Copy to Clipboard Toggle word wrap

3.2.4. OIDC request filters

You can filter OIDC requests made by Quarkus to the OIDC provider by registering one or more OidcRequestFilter implementations, which can update or add new request headers and can also log requests.

For example:

package io.quarkus.it.keycloak;

import io.quarkus.oidc.OidcConfigurationMetadata;
import jakarta.enterprise.context.ApplicationScoped;

import io.quarkus.arc.Unremovable;
import io.quarkus.oidc.common.OidcRequestContext;
import io.quarkus.oidc.common.OidcRequestFilter;

@ApplicationScoped
@Unremovable
public class OidcTokenRequestCustomizer implements OidcRequestFilter {
    @Override
    public void filter(OidcRequestContext requestContext) {
        OidcConfigurationMetadata metadata = requestContext.contextProperties().get(OidcConfigurationMetadata.class.getName()); 
1

        // Metadata URI is absolute, request URI value is relative
        if (metadata.getTokenUri().endsWith(requestContext.request().uri())) { 
2

            requestContext.request().putHeader("TokenGrantDigest", calculateDigest(requestContext.requestBody().toString()));
        }
    }
    private String calculateDigest(String bodyString) {
        // Apply the required digest algorithm to the body string
    }
}
Copy to Clipboard Toggle word wrap
1
Get OidcConfigurationMetadata, which contains all supported OIDC endpoint addresses.
2
Use OidcConfigurationMetadata to filter requests to the OIDC token endpoint only.

Alternatively, you can use an @OidcEndpoint annotation to apply this filter to responses from the OIDC discovery endpoint only:

package io.quarkus.it.keycloak;

import jakarta.enterprise.context.ApplicationScoped;

import io.quarkus.arc.Unremovable;
import io.quarkus.oidc.common.OidcEndpoint;
import io.quarkus.oidc.common.OidcEndpoint.Type;
import io.quarkus.oidc.common.OidcRequestContext;
import io.quarkus.oidc.common.OidcRequestFilter;

@ApplicationScoped
@Unremovable
@OidcEndpoint(value = Type.DISCOVERY) 
1

public class OidcDiscoveryRequestCustomizer implements OidcRequestFilter {

    @Override
    public void filter(OidcRequestContext requestContext) {
        requestContext.request().putHeader("Discovery", "OK");
    }
}
Copy to Clipboard Toggle word wrap
1
Restrict this filter to requests targeting the OIDC discovery endpoint only.

OidcRequestContextProperties can be used to access request properties. Currently, you can use a tenand_id key to access the OIDC tenant id and a grant_type key to access the grant type which the OIDC provider uses to acquire tokens. The grant_type can only be set to either authorization_code or refresh_token grant type, when requests are made to the token endpoint. It is null in all other cases.

3.2.5. OIDC response filters

You can filter responses from the OIDC providers by registering one or more OidcResponseFilter implementations, which can check the response status, headers and body in order to log them or perform other actions.

You can have a single filter intercepting all the OIDC responses, or use an @OidcEndpoint annotation to apply this filter to the specific endpoint responses only. For example:

package io.quarkus.it.keycloak;

import jakarta.enterprise.context.ApplicationScoped;

import io.quarkus.arc.Unremovable;
import io.quarkus.logging.Log;
import io.quarkus.oidc.common.OidcEndpoint;
import io.quarkus.oidc.common.OidcEndpoint.Type;
import io.quarkus.oidc.common.OidcResponseFilter;
import io.quarkus.oidc.common.runtime.OidcConstants;
import io.quarkus.oidc.runtime.OidcUtils;

@ApplicationScoped
@Unremovable
@OidcEndpoint(value = Type.TOKEN) 
1

public class TokenEndpointResponseFilter implements OidcResponseFilter {

    @Override
    public void filter(OidcResponseContext rc) {
        String contentType = rc.responseHeaders().get("Content-Type"); 
2

        if (contentType.equals("application/json")
                && OidcConstants.AUTHORIZATION_CODE.equals(rc.requestProperties().get(OidcConstants.GRANT_TYPE)) 
3

                && "code-flow-user-info-cached-in-idtoken".equals(rc.requestProperties().get(OidcUtils.TENANT_ID_ATTRIBUTE)) 
4

                && rc.responseBody().toJsonObject().containsKey("id_token")) { 
5

            Log.debug("Authorization code completed for tenant 'code-flow-user-info-cached-in-idtoken'");
        }
    }
}
Copy to Clipboard Toggle word wrap
1
Restrict this filter to requests targeting the OIDC token endpoint only.
2
Check the response Content-Type header.
3 4
Use OidcRequestContextProperties request properties to check only an authorization_code token grant response for the code-flow-user-info-cached-in-idtoken tenant.
5
Confirm the response JSON contains an id_token property.

3.2.6. Redirecting to and from the OIDC provider

When a user is redirected to the OIDC provider to authenticate, the redirect URL includes a redirect_uri query parameter, which indicates to the provider where the user has to be redirected to when the authentication is complete. In our case, this is the Quarkus application.

Quarkus sets this parameter to the current application request URL by default. For example, if a user is trying to access a Quarkus service endpoint at http://localhost:8080/service/1, then the redirect_uri parameter is set to http://localhost:8080/service/1. Similarly, if the request URL is http://localhost:8080/service/2, then the redirect_uri parameter is set to http://localhost:8080/service/2.

Some OIDC providers require the redirect_uri to have the same value for a given application, for example, http://localhost:8080/service/callback, for all the redirect URLs. In such cases, a quarkus.oidc.authentication.redirect-path property has to be set. For example, quarkus.oidc.authentication.redirect-path=/service/callback, and Quarkus will set the redirect_uri parameter to an absolute URL such as http://localhost:8080/service/callback, which will be the same regardless of the current request URL.

If quarkus.oidc.authentication.redirect-path is set, but you need the original request URL to be restored after the user is redirected back to a unique callback URL, for example, http://localhost:8080/service/callback, set quarkus.oidc.authentication.restore-path-after-redirect property to true. This will restore the request URL such as http://localhost:8080/service/1.

3.2.6.1. Customizing authentication requests

By default, only the response_type (set to code), scope (set to openid), client_id, redirect_uri, and state properties are passed as HTTP query parameters to the OIDC provider’s authorization endpoint when the user is redirected to it to authenticate.

You can add more properties to it with quarkus.oidc.authentication.extra-params. For example, some OIDC providers might choose to return the authorization code as part of the redirect URI’s fragment, which would break the authentication process. The following example shows how you can work around this issue:

quarkus.oidc.authentication.extra-params.response_mode=query
Copy to Clipboard Toggle word wrap

See also the OIDC redirect filters section explaining how a custom OidcRedirectFilter can be used to customize OIDC redirects, including those to the OIDC authorization endpoint.

When the user is redirected to the OIDC authorization endpoint to authenticate and, if necessary, authorize the Quarkus application, this redirect request might fail, for example, when an invalid scope is included in the redirect URI. In such cases, the provider redirects the user back to Quarkus with error and error_description parameters instead of the expected code parameter.

For example, this can happen when an invalid scope or other invalid parameters are included in the redirect to the provider.

In such cases, an HTTP 401 error is returned by default. However, you can request that a custom public error endpoint be called to return a more user-friendly HTML error page. To do this, set the quarkus.oidc.authentication.error-path property, as shown in the following example:

quarkus.oidc.authentication.error-path=/error
Copy to Clipboard Toggle word wrap

Ensure that the property starts with a forward slash (/) character and the path is relative to the base URI of the current endpoint. For example, if it is set to '/error' and the current request URI is https://localhost:8080/callback?error=invalid_scope, then a final redirect is made to https://localhost:8080/error?error=invalid_scope.

Important

To prevent the user from being redirected to this page to be re-authenticated, ensure that this error endpoint is a public resource.

3.2.7. OIDC redirect filters

You can register one or more io.quarkus.oidc.OidcRedirectFilter implementations to filter OIDC redirects to OIDC authorization and logout endpoints but also local redirects to custom error and session expired pages. Custom OidcRedirectFilter can add additional query parameters, response headers and set new cookies.

For example, the following simple custom OidcRedirectFilter adds an additional query parameter and a custom response header for all redirect requests that can be done by Quarkus OIDC:

package io.quarkus.it.keycloak;

import jakarta.enterprise.context.ApplicationScoped;

import io.quarkus.arc.Unremovable;
import io.quarkus.oidc.OidcRedirectFilter;

@ApplicationScoped
@Unremovable
public class GlobalOidcRedirectFilter implements OidcRedirectFilter {

    @Override
    public void filter(OidcRedirectContext context) {
        if (context.redirectUri().contains("/session-expired-page")) {
            context.additionalQueryParams().add("redirect-filtered", "true,"); 
1

            context.routingContext().response().putHeader("Redirect-Filtered", "true"); 
2

        }
    }

}
Copy to Clipboard Toggle word wrap
1
Add an additional query parameter. Note the queury names and values are URL-encoded by Quarkus OIDC, a redirect-filtered=true%20C query parameter is added to the redirect URI in this case.
2
Add a custom HTTP response header.

See also the Customizing authentication requests section how to configure additional query parameters for OIDC authorization point.

Custom OidcRedirectFilter for local error and session expired pages can also create secure cookies to help with generating such pages.

For example, let’s assume you need to redirect the current user whose session has expired to a custom session expired page available at http://localhost:8080/session-expired-page. The following custom OidcRedirectFilter encrypts the user name in a custom session_expired cookie using an OIDC tenant client secret:

package io.quarkus.it.keycloak;

import jakarta.enterprise.context.ApplicationScoped;

import org.eclipse.microprofile.jwt.Claims;

import io.quarkus.arc.Unremovable;
import io.quarkus.oidc.AuthorizationCodeTokens;
import io.quarkus.oidc.OidcRedirectFilter;
import io.quarkus.oidc.Redirect;
import io.quarkus.oidc.Redirect.Location;
import io.quarkus.oidc.TenantFeature;
import io.quarkus.oidc.runtime.OidcUtils;
import io.smallrye.jwt.build.Jwt;

@ApplicationScoped
@Unremovable
@TenantFeature("tenant-refresh")
@Redirect(Location.SESSION_EXPIRED_PAGE) 
1

public class SessionExpiredOidcRedirectFilter implements OidcRedirectFilter {

    @Override
    public void filter(OidcRedirectContext context) {

        if (context.redirectUri().contains("/session-expired-page")) {
        AuthorizationCodeTokens tokens = context.routingContext().get(AuthorizationCodeTokens.class.getName()); 
2

        String userName = OidcUtils.decodeJwtContent(tokens.getIdToken()).getString(Claims.preferred_username.name()); 
3

        String jwe = Jwt.preferredUserName(userName).jwe()
                .encryptWithSecret(context.oidcTenantConfig().credentials.secret.get()); 
4

        OidcUtils.createCookie(context.routingContext(), context.oidcTenantConfig(), "session_expired",
                jwe + "|" + context.oidcTenantConfig().tenantId.get(), 10); 
5

     }
    }
}
Copy to Clipboard Toggle word wrap
1
Make sure this redirect filter is only called during a redirect to the session expired page.
2
Access AuthorizationCodeTokens tokens associated with the now expired session as a RoutingContext attribute.
3
Decode ID token claims and get a user name.
4
Save the user name in a JWT token encrypted with the current OIDC tenant’s client secret.
5
Create a custom session_expired cookie valid for 5 seconds which joins the encrypted token and a tenant id using a "|" separator. Recording a tenant id in a custom cookie can help to generate correct session expired pages in a multi-tenant OIDC setup.

Next, a public JAX-RS resource which generates session expired pages can use this cookie to create a page tailored for this user and the corresponding OIDC tenant, for example:

package io.quarkus.it.keycloak;

import jakarta.inject.Inject;
import jakarta.ws.rs.CookieParam;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;

import org.eclipse.microprofile.jwt.Claims;
import org.eclipse.microprofile.jwt.JsonWebToken;

import io.quarkus.oidc.OidcTenantConfig;
import io.quarkus.oidc.runtime.OidcUtils;
import io.quarkus.oidc.runtime.TenantConfigBean;
import io.smallrye.jwt.auth.principal.DefaultJWTParser;
import io.vertx.ext.web.RoutingContext;

@Path("/session-expired-page")
public class SessionExpiredResource {
    @Inject
    RoutingContext context;

    @Inject
    TenantConfigBean tenantConfig; 
1


    @GET
    public String sessionExpired(@CookieParam("session_expired") String sessionExpired) throws Exception {
        // Cookie format: jwt|<tenant id>

        String[] pair = sessionExpired.split("\\|"); 
2

        OidcTenantConfig oidcConfig = tenantConfig.getStaticTenantsConfig().get(pair[1]).getOidcTenantConfig(); 
3

        JsonWebToken jwt = new DefaultJWTParser().decrypt(pair[0], oidcConfig.credentials.secret.get()); 
4

        OidcUtils.removeCookie(context, oidcConfig, "session_expired"); 
5

        return jwt.getClaim(Claims.preferred_username) + ", your session has expired. "
                + "Please login again at http://localhost:8081/" + oidcConfig.tenantId.get(); 
6

    }
}
Copy to Clipboard Toggle word wrap
1
Inject TenantConfigBean which can be used to access all the current OIDC tenant configurations.
2
Split the custom cookie value into 2 parts, first part is the encrypted token, last part is the tenant id.
3
Get the OIDC tenant configuration.
4
Decrypt the cookie value using the OIDC tenant’s client secret.
5
Remove the custom cookie.
6
Use the username in the decrypted token and the tenant id to generate the service expired page response.

3.2.8. Accessing authorization data

You can access information about authorization in different ways.

3.2.8.1. Accessing ID and access tokens

The OIDC code authentication mechanism acquires three tokens during the authorization code flow: ID token, access token, and refresh token.

The ID token is always a JWT token and represents a user authentication with the JWT claims. You can use this to get the issuing OIDC endpoint, the username, and other information called claims. You can access ID token claims by injecting JsonWebToken with an IdToken qualifier:

import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import org.eclipse.microprofile.jwt.JsonWebToken;
import io.quarkus.oidc.IdToken;
import io.quarkus.security.Authenticated;

@Path("/web-app")
@Authenticated
public class ProtectedResource {

    @Inject
    @IdToken
    JsonWebToken idToken;

    @GET
    public String getUserName() {
        return idToken.getName();
    }
}
Copy to Clipboard Toggle word wrap

The OIDC web-app application usually uses the access token to access other endpoints on behalf of the currently logged-in user. You can access the raw access token as follows:

import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import org.eclipse.microprofile.jwt.JsonWebToken;
import io.quarkus.oidc.AccessTokenCredential;
import io.quarkus.security.Authenticated;

@Path("/web-app")
@Authenticated
public class ProtectedResource {

    @Inject
    JsonWebToken accessToken;

    // or
    // @Inject
    // AccessTokenCredential accessTokenCredential;

    @GET
    public String getReservationOnBehalfOfUser() {
        String rawAccessToken = accessToken.getRawToken();
        //or
        //String rawAccessToken = accessTokenCredential.getToken();

        // Use the raw access token to access a remote endpoint.
        // For example, use RestClient to set this token as a `Bearer` scheme value of the HTTP `Authorization` header:
        // `Authorization: Bearer rawAccessToken`.
        return getReservationfromRemoteEndpoint(rawAccesstoken);
    }
}
Copy to Clipboard Toggle word wrap
Note

When an authorization code flow access token is injected as JsonWebToken, its verification is automatically enabled, in addition to the mandatory ID token verification. If really needed, you can disable this code flow access token verification with quarkus.oidc.authentication.verify-access-token=false.

Note

AccessTokenCredential is used if the access token issued to the Quarkus web-app application is opaque (binary) and cannot be parsed to a JsonWebToken or if the inner content is necessary for the application.

Injection of the JsonWebToken and AccessTokenCredential is supported in both @RequestScoped and @ApplicationScoped contexts.

Quarkus OIDC uses the refresh token to refresh the current ID and access tokens as part of its session management process.

3.2.8.2. User info

If the ID token does not provide enough information about the currently authenticated user, you can get more information from the UserInfo endpoint. Set the quarkus.oidc.authentication.user-info-required=true property to request a UserInfo JSON object from the OIDC UserInfo endpoint.

A request is sent to the OIDC provider UserInfo endpoint by using the access token returned with the authorization code grant response, and an io.quarkus.oidc.UserInfo (a simple jakarta.json.JsonObject wrapper) object is created. io.quarkus.oidc.UserInfo can be injected or accessed as a SecurityIdentity userinfo attribute.

quarkus.oidc.authentication.user-info-required is automatically enabled if one of these conditions is met:

  • if quarkus.oidc.roles.source is set to userinfo or quarkus.oidc.token.verify-access-token-with-user-info is set to true or quarkus.oidc.authentication.id-token-required is set to false, the current OIDC tenant must support a UserInfo endpoint in these cases.
  • if io.quarkus.oidc.UserInfo injection point is detected but only if the current OIDC tenant supports a UserInfo endpoint.

The current tenant’s discovered OpenID Connect configuration metadata is represented by io.quarkus.oidc.OidcConfigurationMetadata and can be injected or accessed as a SecurityIdentity configuration-metadata attribute.

The default tenant’s OidcConfigurationMetadata is injected if the endpoint is public.

The way the roles are mapped to the SecurityIdentity roles from the verified tokens is identical to how it is done for the Bearer tokens. The only difference is that ID token is used as a source of the roles by default.

Note

If you use Keycloak, set a microprofile-jwt client scope for the ID token to contain a groups claim. For more information, see the Keycloak server administration guide.

However, depending on your OIDC provider, roles might be stored in the access token or the user info.

If the access token contains the roles and this access token is not meant to be propagated to the downstream endpoints, then set quarkus.oidc.roles.source=accesstoken.

If UserInfo is the source of the roles, then set quarkus.oidc.roles.source=userinfo, and if needed, quarkus.oidc.roles.role-claim-path.

Additionally, you can also use a custom SecurityIdentityAugmentor to add the roles. For more information, see SecurityIdentity customization. You can also map SecurityIdentity roles created from token claims to deployment-specific roles with the HTTP Security policy.

A core part of the authentication process is ensuring the chain of trust and validity of the information. This is done by ensuring tokens can be trusted.

3.2.9.1. Token verification and introspection

The verification process of OIDC authorization code flow tokens follows the Bearer token authentication token verification and introspection logic. For more information, see the Token verification and introspection section of the "Quarkus OpenID Connect (OIDC) Bearer token authentication" guide.

Note

With Quarkus web-app applications, only the IdToken is verified by default because the access token is not used to access the current Quarkus web-app endpoint and is intended to be propagated to the services expecting this access token. If you expect the access token to contain the roles required to access the current Quarkus endpoint (quarkus.oidc.roles.source=accesstoken), then it will also be verified.

3.2.9.2. Token introspection and UserInfo cache

Code flow access tokens are not introspected unless they are expected to be the source of roles. However, they will be used to get UserInfo. There will be one or two remote calls with the code flow access token if the token introspection, UserInfo, or both are required.

For more information about using the default token cache or registering a custom cache implementation, see Token introspection and UserInfo cache.

3.2.9.3. JSON web token claim verification

For information about the claim verification, including the iss (issuer) claim, see the JSON Web Token claim verification section. It applies to ID tokens and also to access tokens in a JWT format, if the web-app application has requested the access token verification.

3.2.9.4. Jose4j Validator

You can register a custom Jose4j Validator to customize the JWT claim verification process. See the Jose4j section for more information.

3.2.10. Proof Key for Code Exchange (PKCE)

Proof Key for Code Exchange (PKCE) minimizes the risk of authorization code interception.

While PKCE is of primary importance to public OIDC clients, such as SPA scripts running in a browser, it can also provide extra protection to Quarkus OIDC web-app applications. With PKCE, Quarkus OIDC web-app applications act as confidential OIDC clients that can securely store the client secret and use it to exchange the code for the tokens.

You can enable PKCE for your OIDC web-app endpoint with a quarkus.oidc.authentication.pkce-required property and a 32-character secret that is required to encrypt the PKCE code verifier in the state cookie, as shown in the following example:

quarkus.oidc.authentication.pkce-required=true
quarkus.oidc.authentication.state-secret=eUk1p7UB3nFiXZGUXi0uph1Y9p34YhBU
Copy to Clipboard Toggle word wrap

If you already have a 32-character client secret, you do not need to set the quarkus.oidc.authentication.pkce-secret property unless you prefer to use a different secret key. This secret will be auto-generated if it is not configured and if the fallback to the client secret is not possible in cases where the client secret is less than 16 characters long.

The secret key is required to encrypt a randomly generated PKCE code_verifier while the user is redirected with the code_challenge query parameter to an OIDC provider to authenticate. The code_verifier is decrypted when the user is redirected back to Quarkus and sent to the token endpoint alongside the code, client secret, and other parameters to complete the code exchange. The provider will fail the code exchange if a SHA256 digest of the code_verifier does not match the code_challenge that was provided during the authentication request.

Another important requirement for authentication is to ensure that the data the session is based on is up-to-date without requiring the user to authenticate for every single request. There are also situations where a logout event is explicitly requested. Use the following key points to find the right balance for securing your Quarkus applications:

3.2.11.1. Cookies

The OIDC adapter uses cookies to keep the session, code flow, and post-logout state. This state is a key element controlling the lifetime of authentication data.

Use the quarkus.oidc.authentication.cookie-path property to ensure that the same cookie is visible when you access protected resources with overlapping or different roots. For example:

  • /index.html and /web-app/service
  • /web-app/service1 and /web-app/service2
  • /web-app1/service and /web-app2/service

By default, quarkus.oidc.authentication.cookie-path is set to / but you can change this to a more specific path if required, for example, /web-app.

To set the cookie path dynamically, configure the quarkus.oidc.authentication.cookie-path-header property. For example, to set the cookie path dynamically by using the value of the X-Forwarded-Prefix HTTP header, configure the property to quarkus.oidc.authentication.cookie-path-header=X-Forwarded-Prefix.

If quarkus.oidc.authentication.cookie-path-header is set but no configured HTTP header is available in the current request, then the quarkus.oidc.authentication.cookie-path will be checked.

If your application is deployed across multiple domains, set the quarkus.oidc.authentication.cookie-domain property so that the session cookie is visible to all protected Quarkus services. For example, if you have Quarkus services deployed on the following two domains, then you must set the quarkus.oidc.authentication.cookie-domain property to company.net:

  • https://whatever.wherever.company.net/
  • https://another.address.company.net/
3.2.11.2. State cookies

State cookies are used to support authorization code flow completion. When an authorization code flow is started, Quarkus creates a state cookie and a matching state query parameter, before redirecting the user to the OIDC provider. When the user is redirected back to Quarkus to complete the authorization code flow, Quarkus expects that the request URI must contain the state query parameter and it must match the current state cookie value.

The default state cookie age is 5 mins and you can change it with a quarkus.oidc.authentication.state-cookie-age Duration property.

Quarkus creates a unique state cookie name every time a new authorization code flow is started to support multi-tab authentication. Many concurrent authentication requests on behalf of the same user may cause a lot of state cookies be created. If you do not want to allow your users use multiple browser tabs to authenticate then it is recommended to disable it with quarkus.oidc.authentication.allow-multiple-code-flows=false. It also ensures that the same state cookie name is created for every new user authentication.

OIDC CodeAuthenticationMechanism uses the default io.quarkus.oidc.TokenStateManager interface implementation to keep the ID, access, and refresh tokens returned in the authorization code or refresh grant responses in an encrypted session cookie.

It makes Quarkus OIDC endpoints completely stateless and it is recommended to follow this strategy to achieve the best scalability results.

See the Session cookie and custom TokenStateManager section for alternative methods of token storage. This is ideal for those seeking customized solutions for token state management, especially when standard server-side storage does not meet your specific requirements.

You can configure the default TokenStateManager to avoid saving an access token in the session cookie and to only keep ID and refresh tokens or a single ID token only.

An access token is only required if the endpoint needs to do the following actions:

  • Retrieve UserInfo
  • Access the downstream service with this access token
  • Use the roles associated with the access token, which are checked by default

In such cases, use the quarkus.oidc.token-state-manager.strategy property to configure the token state strategy as follows:

Expand
To…​Set the property to …​

Keep the ID and refresh tokens only

quarkus.oidc.token-state-manager.strategy=id-refresh-tokens

Keep the ID token only

quarkus.oidc.token-state-manager.strategy=id-token

If your chosen session cookie strategy combines tokens and generates a large session cookie value that is greater than 4KB, some browsers might not be able to handle such cookie sizes. This can occur when the ID, access, and refresh tokens are JWT tokens and the selected strategy is keep-all-tokens or with ID and refresh tokens when the strategy is id-refresh-token. To work around this issue, you can set quarkus.oidc.token-state-manager.split-tokens=true to create a unique session token for each token.

The default TokenStateManager encrypts the tokens before storing them in the session cookie. The following example shows how you configure it to split the tokens and encrypt them:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.oidc.client-id=quarkus-app
quarkus.oidc.credentials.secret=secret
quarkus.oidc.application-type=web-app
quarkus.oidc.token-state-manager.split-tokens=true
quarkus.oidc.token-state-manager.encryption-secret=eUk1p7UB3nFiXZGUXi0uph1Y9p34YhBU
Copy to Clipboard Toggle word wrap

The token encryption secret must be at least 32 characters long. If this key is not configured, then either quarkus.oidc.credentials.secret or quarkus.oidc.credentials.jwt.secret will be hashed to create an encryption key.

Configure the quarkus.oidc.token-state-manager.encryption-secret property if Quarkus authenticates to the OIDC provider by using one of the following authentication methods:

  • mTLS
  • private_key_jwt, where a private RSA or EC key is used to sign a JWT token

Otherwise, a random key is generated, which can be problematic if the Quarkus application is running in the cloud with multiple pods managing the requests.

You can disable token encryption in the session cookie by setting quarkus.oidc.token-state-manager.encryption-required=false.

If you want to customize the way the tokens are associated with the session cookie, register a custom io.quarkus.oidc.TokenStateManager implementation as an @ApplicationScoped CDI bean.

For example, you might want to keep the tokens in a cache cluster and have only a key stored in a session cookie. Note that this approach might introduce some challenges if you need to make the tokens available across multiple microservices nodes.

Here is a simple example:

package io.quarkus.oidc.test;

import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Alternative;
import jakarta.inject.Inject;

import io.quarkus.oidc.AuthorizationCodeTokens;
import io.quarkus.oidc.OidcTenantConfig;
import io.quarkus.oidc.TokenStateManager;
import io.quarkus.oidc.runtime.DefaultTokenStateManager;
import io.smallrye.mutiny.Uni;
import io.vertx.ext.web.RoutingContext;

@ApplicationScoped
@Alternative
@Priority(1)
public class CustomTokenStateManager implements TokenStateManager {

    @Inject
    DefaultTokenStateManager tokenStateManager;

    @Override
    public Uni<String> createTokenState(RoutingContext routingContext, OidcTenantConfig oidcConfig,
            AuthorizationCodeTokens sessionContent, OidcRequestContext<String> requestContext) {
        return tokenStateManager.createTokenState(routingContext, oidcConfig, sessionContent, requestContext)
                .map(t -> (t + "|custom"));
    }

    @Override
    public Uni<AuthorizationCodeTokens> getTokens(RoutingContext routingContext, OidcTenantConfig oidcConfig,
            String tokenState, OidcRequestContext<AuthorizationCodeTokens> requestContext) {
        if (!tokenState.endsWith("|custom")) {
            throw new IllegalStateException();
        }
        String defaultState = tokenState.substring(0, tokenState.length() - 7);
        return tokenStateManager.getTokens(routingContext, oidcConfig, defaultState, requestContext);
    }

    @Override
    public Uni<Void> deleteTokens(RoutingContext routingContext, OidcTenantConfig oidcConfig, String tokenState,
            OidcRequestContext<Void> requestContext) {
        if (!tokenState.endsWith("|custom")) {
            throw new IllegalStateException();
        }
        String defaultState = tokenState.substring(0, tokenState.length() - 7);
        return tokenStateManager.deleteTokens(routingContext, oidcConfig, defaultState, requestContext);
    }
}
Copy to Clipboard Toggle word wrap

For information about the default TokenStateManager storing tokens in an encrypted session cookie, see Session cookie and default TokenStateManager.

3.2.12. Logout and expiration

There are two main ways for the authentication information to expire: the tokens expired and were not renewed or an explicit logout operation was triggered.

Let’s start with explicit logout operations.

3.2.12.1. User-initiated logout

Users can request a logout by sending a request to the Quarkus endpoint logout path set with a quarkus.oidc.logout.path property. For example, if the endpoint address is https://application.com/webapp and the quarkus.oidc.logout.path is set to /logout, then the logout request must be sent to https://application.com/webapp/logout.

This logout request starts an RP-initiated logout. The user will be redirected to the OIDC provider to log out, where they can be asked to confirm the logout is indeed intended.

The user will be returned to the endpoint post-logout page once the logout has been completed and if the quarkus.oidc.logout.post-logout-path property is set. For example, if the endpoint address is https://application.com/webapp and the quarkus.oidc.logout.post-logout-path is set to /signin, then the user will be returned to https://application.com/webapp/signin. Note, this URI must be registered as a valid post_logout_redirect_uri in the OIDC provider.

If the quarkus.oidc.logout.post-logout-path is set, then a q_post_logout cookie will be created and a matching state query parameter will be added to the logout redirect URI and the OIDC provider will return this state once the logout has been completed. It is recommended for the Quarkus web-app applications to check that a state query parameter matches the value of the q_post_logout cookie, which can be done, for example, in a Jakarta REST filter.

Note that a cookie name varies when using OpenID Connect Multi-Tenancy. For example, it will be named q_post_logout_tenant_1 for a tenant with a tenant_1 ID, and so on.

Here is an example of how to configure a Quarkus application to initiate a logout flow:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.oidc.client-id=frontend
quarkus.oidc.credentials.secret=secret
quarkus.oidc.application-type=web-app

quarkus.oidc.logout.path=/logout
# Logged-out users should be returned to the /welcome.html site which will offer an option to re-login:
quarkus.oidc.logout.post-logout-path=/welcome.html

# Only the authenticated users can initiate a logout:
quarkus.http.auth.permission.authenticated.paths=/logout
quarkus.http.auth.permission.authenticated.policy=authenticated

# All users can see the Welcome page:
quarkus.http.auth.permission.public.paths=/welcome.html
quarkus.http.auth.permission.public.policy=permit
Copy to Clipboard Toggle word wrap

You might also want to set quarkus.oidc.authentication.cookie-path to a path value common to all the application resources, which is / in this example. For more information, see the Cookies section.

Note

Some OIDC providers do not support a RP-initiated logout specification and do not return an OpenID Connect well-known end_session_endpoint metadata property. However, this is not a problem for Quarkus because the specific logout mechanisms of such OIDC providers only differ in how the logout URL query parameters are named.

According to the RP-initiated logout specification, the quarkus.oidc.logout.post-logout-path property is represented as a post_logout_redirect_uri query parameter, which is not recognized by the providers that do not support this specification.

You can use quarkus.oidc.logout.post-logout-url-param to work around this issue. You can also request more logout query parameters added with quarkus.oidc.logout.extra-params. For example, here is how you can support a logout with Auth0:

quarkus.oidc.auth-server-url=https://dev-xxx.us.auth0.com
quarkus.oidc.client-id=redacted
quarkus.oidc.credentials.secret=redacted
quarkus.oidc.application-type=web-app

quarkus.oidc.tenant-logout.logout.path=/logout
quarkus.oidc.tenant-logout.logout.post-logout-path=/welcome.html

# Auth0 does not return the `end_session_endpoint` metadata property. Instead, you must configure it:
quarkus.oidc.end-session-path=v2/logout
# Auth0 will not recognize the 'post_logout_redirect_uri' query parameter so ensure it is named as 'returnTo':
quarkus.oidc.logout.post-logout-uri-param=returnTo

# Set more properties if needed.
# For example, if 'client_id' is provided, then a valid logout URI should be set as the Auth0 Application property, without it - as Auth0 Tenant property:
quarkus.oidc.logout.extra-params.client_id=${quarkus.oidc.client-id}
Copy to Clipboard Toggle word wrap
3.2.12.2. Back-channel logout

The OIDC provider can force the logout of all applications by using the authentication data. This is known as back-channel logout. In this case, the OIDC will call a specific URL from each application to trigger that logout.

OIDC providers use Back-channel logout to log out the current user from all the applications into which this user is currently logged in, bypassing the user agent.

You can configure Quarkus to support Back-channel logout as follows:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.oidc.client-id=frontend
quarkus.oidc.credentials.secret=secret
quarkus.oidc.application-type=web-app

quarkus.oidc.logout.backchannel.path=/back-channel-logout
Copy to Clipboard Toggle word wrap

The absolute back-channel logout URL is calculated by adding quarkus.oidc.back-channel-logout.path to the current endpoint URL, for example, http://localhost:8080/back-channel-logout. You will need to configure this URL in the admin console of your OIDC provider.

You will also need to configure a token age property for the logout token verification to succeed if your OIDC provider does not set an expiry claim in the current logout token. For example, set quarkus.oidc.token.age=10S to ensure that no more than 10 seconds elapse since the logout token’s iat (issued at) time.

3.2.12.3. Front-channel logout

You can use Front-channel logout to log out the current user directly from the user agent, for example, its browser. It is similar to Back-channel logout but the logout steps are executed by the user agent, such as the browser, and not in the background by the OIDC provider. This option is rarely used.

You can configure Quarkus to support Front-channel logout as follows:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.oidc.client-id=frontend
quarkus.oidc.credentials.secret=secret
quarkus.oidc.application-type=web-app

quarkus.oidc.logout.frontchannel.path=/front-channel-logout
Copy to Clipboard Toggle word wrap

This path will be compared to the current request’s path, and the user will be logged out if these paths match.

3.2.12.4. Local logout

User-initiated logout will log the user out of the OIDC provider. If it is used as single sign-on, it might not be what you require. If, for example, your OIDC provider is Google, you will be logged out from Google and its services. Instead, the user might just want to log out of that specific application. Another use case might be when the OIDC provider does not have a logout endpoint.

By using OidcSession, you can support a local logout, which means that only the local session cookie is cleared, as shown in the following example:

import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;

import io.quarkus.oidc.OidcSession;

@Path("/service")
public class ServiceResource {

    @Inject
    OidcSession oidcSession;

    @GET
    @Path("logout")
    public String logout() {
        oidcSession.logout().await().indefinitely();
        return "You are logged out";
    }
}
Copy to Clipboard Toggle word wrap
3.2.12.5. Using OidcSession for local logout

io.quarkus.oidc.OidcSession is a wrapper around the current IdToken, which can help to perform a Local logout, retrieve the current session’s tenant identifier, and check when the session will expire. More useful methods will be added to it over time.

3.2.12.6. Session management

By default, logout is based on the expiration time of the ID token issued by the OIDC provider. When the ID token expires, the current user session at the Quarkus endpoint is invalidated, and the user is redirected to the OIDC provider again to authenticate. If the session at the OIDC provider is still active, users are automatically re-authenticated without needing to provide their credentials again.

The current user session can be automatically extended by enabling the quarkus.oidc.token.refresh-expired property. If set to true, when the current ID token expires, a refresh token grant will be used to refresh the ID token as well as access and refresh tokens.

Tip

If you have a single page application for service applications where your OIDC provider script such as keycloak.js is managing an authorization code flow, then that script will also control the SPA authentication session lifespan.

If you work with a Quarkus OIDC web-app application, then the Quarkus OIDC code authentication mechanism manages the user session lifespan.

To use the refresh token, you should carefully configure the session cookie age. The session age should be longer than the ID token lifespan and close to or equal to the refresh token lifespan.

You calculate the session age by adding the lifespan value of the current ID token and the values of the quarkus.oidc.authentication.session-age-extension and quarkus.oidc.token.lifespan-grace properties.

Tip

You use only the quarkus.oidc.authentication.session-age-extension property to significantly extend the session lifespan, if required. You use the quarkus.oidc.token.lifespan-grace property only to consider some small clock skews.

When the current authenticated user returns to the protected Quarkus endpoint and the ID token associated with the session cookie has expired, then, by default, the user is automatically redirected to the OIDC Authorization endpoint to re-authenticate. The OIDC provider might challenge the user again if the session between the user and this OIDC provider is still active, which might happen if the session is configured to last longer than the ID token.

If the quarkus.oidc.token.refresh-expired is set to true, then the expired ID token (and the access token) is refreshed by using the refresh token returned with the initial authorization code grant response. This refresh token might also be recycled (refreshed) itself as part of this process. As a result, the new session cookie is created, and the session is extended.

Note

In instances where the user is not very active, you can use the quarkus.oidc.authentication.session-age-extension property to help handle expired ID tokens. If the ID token expires, the session cookie might not be returned to the Quarkus endpoint during the next user request as the cookie lifespan would have elapsed. Quarkus assumes that this request is the first authentication request. Set quarkus.oidc.authentication.session-age-extension to be reasonably long for your barely-active users and in accordance with your security policies.

You can go one step further and proactively refresh ID tokens or access tokens that are about to expire. Set quarkus.oidc.token.refresh-token-time-skew to the value you want to anticipate the refresh. If, during the current user request, it is calculated that the current ID token will expire within this quarkus.oidc.token.refresh-token-time-skew, then it is refreshed, and the new session cookie is created. This property should be set to a value that is less than the ID token lifespan; the closer it is to this lifespan value, the more often the ID token is refreshed.

You can further optimize this process by having a simple JavaScript function ping your Quarkus endpoint periodically to emulate the user activity, which minimizes the time frame during which the user might have to be re-authenticated.

Note

When the session can not be refreshed, the currently authenticated user is redirected to the OIDC provider to re-authenticate. However, the user experience may not be ideal in such cases, if the user, after an earlier successful authentication, is suddently seeing an OIDC authentication challenge screen when trying to access an application page.

Instead, you can request that the user is redirected to a public, application specific session expired page first. This page informs the user that the session has now expired and advise to re-authenticate by following a link to a secured application welcome page. The user clicks on the link and Quarkus OIDC enforces a redirect to the OIDC provider to re-authenticate. Use quarkus.oidc.authentication.session-expired-page relative path property, if you’d like to do it.

For example, setting quarkus.oidc.authentication.session-expired-page=/session-expired-page will ensure that the user whose session has expired is redirected to http://localhost:8080/session-expired-page, assuming the application is available at http://localhost:8080.

See also the OIDC redirect filters section explaining how a custom OidcRedirectFilter can be used to customize OIDC redirects, including those to the session expired pages.

Note

You cannot extend the user session indefinitely. The returning user with the expired ID token will have to re-authenticate at the OIDC provider endpoint once the refresh token has expired.

Some well-known providers such as GitHub or LinkedIn are not OpenID Connect providers, but OAuth2 providers that support the authorization code flow. For example, GitHub OAuth2 and LinkedIn OAuth2. Remember, OIDC is built on top of OAuth2.

The main difference between OIDC and OAuth2 providers is that OIDC providers return an ID Token that represents a user authentication, in addition to the standard authorization code flow access and refresh tokens returned by OAuth2 providers.

OAuth2 providers such as GitHub do not return IdToken, and the user authentication is implicit and indirectly represented by the access token. This access token represents an authenticated user authorizing the current Quarkus web-app application to access some data on behalf of the authenticated user.

For OIDC, you validate the ID token as proof of authentication validity whereas in the case of OAuth2, you validate the access token. This is done by subsequently calling an endpoint that requires the access token and that typically returns user information. This approach is similar to the OIDC UserInfo approach, with UserInfo fetched by Quarkus OIDC on your behalf.

For example, when working with GitHub, the Quarkus endpoint can acquire an access token, which allows the Quarkus endpoint to request a GitHub profile for the current user.

To support the integration with such OAuth2 servers, quarkus-oidc needs to be configured a bit differently to allow the authorization code flow responses without IdToken: quarkus.oidc.authentication.id-token-required=false.

Note

Even though you configure the extension to support the authorization code flows without IdToken, an internal IdToken is generated to standardize the way quarkus-oidc operates. You use an internal IdToken to support the authentication session and to avoid redirecting the user to the provider, such as GitHub, on every request. In this case, the IdToken age is set to the value of a standard expires_in property in the authorization code flow response. You can use a quarkus.oidc.authentication.internal-id-token-lifespan property to customize the ID token age. The default ID token age is 5 minutes, which you can extend further as described in the session management section.

This simplifies how you handle an application that supports multiple OIDC providers.

The next step is to ensure that the returned access token can be useful and is valid to the current Quarkus endpoint. The first way is to call the OAuth2 provider introspection endpoint by configuring quarkus.oidc.introspection-path, if the provider offers such an endpoint. In this case, you can use the access token as a source of roles using quarkus.oidc.roles.source=accesstoken. If no introspection endpoint is present, you can attempt instead to request UserInfo from the provider as it will at least validate the access token. To do so, specify quarkus.oidc.token.verify-access-token-with-user-info=true. You also need to set the quarkus.oidc.user-info-path property to a URL endpoint that fetches the user info (or to an endpoint protected by the access token). For GitHub, since it does not have an introspection endpoint, requesting the UserInfo is required.

Note

Requiring UserInfo involves making a remote call on every request.

Therefore, UserInfo is embedded in the internal generated IdToken and saved in the encrypted session cookie. It can be disabled with quarkus.oidc.cache-user-info-in-idtoken=false.

Alternatively, you might want to consider caching UserInfo using a default or custom UserInfo cache provider. For more information, see the Token Introspection and UserInfo cache section of the "OpenID Connect (OIDC) Bearer token authentication" guide.

Most well-known social OAuth2 providers enforce rate-limiting so there is a high chance you will prefer to have UserInfo cached.

OAuth2 servers might not support a well-known configuration endpoint. In this case, you must disable the discovery and configure the authorization, token, and introspection and UserInfo endpoint paths manually.

For well-known OIDC or OAuth2 providers, such as Apple, Facebook, GitHub, Google, Microsoft, Spotify, and X (formerly Twitter), Quarkus can help significantly simplify your application’s configuration with the quarkus.oidc.provider property. Here is how you can integrate quarkus-oidc with GitHub after you have created a GitHub OAuth application. Configure your Quarkus endpoint like this:

quarkus.oidc.provider=github
quarkus.oidc.client-id=github_app_clientid
quarkus.oidc.credentials.secret=github_app_clientsecret

# user:email scope is requested by default, use 'quarkus.oidc.authentication.scopes' to request different scopes such as `read:user`.
# See https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps for more information.

# Consider enabling UserInfo Cache
# quarkus.oidc.token-cache.max-size=1000
# quarkus.oidc.token-cache.time-to-live=5M
#
# Or having UserInfo cached inside IdToken itself
# quarkus.oidc.cache-user-info-in-idtoken=true
Copy to Clipboard Toggle word wrap

For more information about configuring other well-known providers, see OpenID Connect providers.

This is all that is needed for an endpoint like this one to return the currently-authenticated user’s profile with GET http://localhost:8080/github/userinfo and access it as the individual UserInfo properties:

package io.quarkus.it.keycloak;

import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;

import io.quarkus.oidc.UserInfo;
import io.quarkus.security.Authenticated;

@Path("/github")
@Authenticated
public class TokenResource {

    @Inject
    UserInfo userInfo;

    @GET
    @Path("/userinfo")
    @Produces("application/json")
    public String getUserInfo() {
        return userInfo.getUserInfoString();
    }
}
Copy to Clipboard Toggle word wrap

If you support more than one social provider with the help of OpenID Connect Multi-Tenancy, for example, Google, which is an OIDC provider that returns IdToken, and GitHub, which is an OAuth2 provider that does not return IdToken and only allows access to UserInfo, then you can have your endpoint working with only the injected SecurityIdentity for both Google and GitHub flows. A simple augmentation of SecurityIdentity will be required where a principal created with the internally-generated IdToken will be replaced with the UserInfo-based principal when the GitHub flow is active:

package io.quarkus.it.keycloak;

import java.security.Principal;

import jakarta.enterprise.context.ApplicationScoped;

import io.quarkus.oidc.UserInfo;
import io.quarkus.security.identity.AuthenticationRequestContext;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.security.identity.SecurityIdentityAugmentor;
import io.quarkus.security.runtime.QuarkusSecurityIdentity;
import io.smallrye.mutiny.Uni;
import io.vertx.ext.web.RoutingContext;

@ApplicationScoped
public class CustomSecurityIdentityAugmentor implements SecurityIdentityAugmentor {

    @Override
    public Uni<SecurityIdentity> augment(SecurityIdentity identity, AuthenticationRequestContext context) {
        RoutingContext routingContext = identity.getAttribute(RoutingContext.class.getName());
        if (routingContext != null && routingContext.normalizedPath().endsWith("/github")) {
	        QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder(identity);
	        UserInfo userInfo = identity.getAttribute("userinfo");
	        builder.setPrincipal(new Principal() {

	            @Override
	            public String getName() {
	                return userInfo.getString("preferred_username");
	            }

	        });
	        identity = builder.build();
        }
        return Uni.createFrom().item(identity);
    }

}
Copy to Clipboard Toggle word wrap

Now, the following code will work when the user signs into your application by using Google or GitHub:

package io.quarkus.it.keycloak;

import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;

import io.quarkus.security.Authenticated;
import io.quarkus.security.identity.SecurityIdentity;

@Path("/service")
@Authenticated
public class TokenResource {

    @Inject
    SecurityIdentity identity;

    @GET
    @Path("/google")
    @Produces("application/json")
    public String getGoogleUserName() {
        return identity.getPrincipal().getName();
    }

    @GET
    @Path("/github")
    @Produces("application/json")
    public String getGitHubUserName() {
        return identity.getPrincipal().getName();
    }
}
Copy to Clipboard Toggle word wrap

Possibly a simpler alternative is to inject both @IdToken JsonWebToken and UserInfo and use JsonWebToken when handling the providers that return IdToken and use UserInfo with the providers that do not return IdToken.

You must ensure that the callback path you enter in the GitHub OAuth application configuration matches the endpoint path where you want the user to be redirected after a successful GitHub authentication and application authorization. In this case, it has to be set to http://localhost:8080/github/userinfo.

You can register the @ApplicationScoped bean which will observe important OIDC authentication events. When a user logs in for the first time, re-authenticates, or refreshes the session, the listener is updated. In the future, more events might be reported. For example:

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;

import io.quarkus.oidc.SecurityEvent;
import io.vertx.ext.web.RoutingContext;

@ApplicationScoped
public class SecurityEventListener {

    public void event(@Observes SecurityEvent event) {
        String tenantId = event.getSecurityIdentity().getAttribute("tenant-id");
        RoutingContext vertxContext = event.getSecurityIdentity().getAttribute(RoutingContext.class.getName());
        vertxContext.put("listener-message", String.format("event:%s,tenantId:%s", event.getEventType().name(), tenantId));
    }
}
Copy to Clipboard Toggle word wrap
Tip

You can listen to other security events as described in the Observe security events section of the Security Tips and Tricks guide.

3.2.15. Token revocation

Sometimes, you may want to revoke the current authorization code flow access and/or refresh tokens. You can revoke tokens with quarkus.oidc.OidcProviderClient which provides access to the OIDC provider’s UserInfo, token introspection and revocation endpoints.

For example, when a local logout with OidcSession is performed, you can use an injected OidcProviderClient to revoke access and refresh tokens associated with the current session:

import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;

import io.quarkus.oidc.AccessTokenCredential;
import io.quarkus.oidc.OidcProviderClient;
import io.quarkus.oidc.OidcSession;
import io.quarkus.oidc.RefreshToken;

import io.smallrye.mutiny.Uni;

@Path("/service")
public class ServiceResource {

    @Inject
    OidcSession oidcSession;

    @Inject
    OidcProviderClient oidcProviderClient;

    @Inject
    AccessTokenCredential accessToken;

    @Inject
    RefreshToken refreshToken;

    @GET
    public Uni<String> logout() {
        return oidcSession.logout() 
1

                   .chain(() -> oidcClient.revokeAccessToken(accessToken.getToken())) 
2

                   .chain(() -> oidcClient.revokeRefreshToken(refreshToken.getToken())) 
3

                   .map((result) -> "You are logged out");
    }
}
Copy to Clipboard Toggle word wrap
1
Do the local logout by clearing the session cookie.
2
Revoke the authorization code flow access token.
3
Revoke the authorization code flow refresh token.

You can also revoke tokens in the security event listeners.

For example, when your application supports a standard User-initiated logout, you can catch a logout event and revoke tokens:

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;

import io.quarkus.oidc.AccessTokenCredential;
import io.quarkus.oidc.OidcProviderClient;
import io.quarkus.oidc.RefreshToken;
import io.quarkus.oidc.SecurityEvent;
import io.quarkus.security.identity.SecurityIdentity;
import io.smallrye.mutiny.Uni;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.ObservesAsync;

@ApplicationScoped
public class SecurityEventListener {

    public CompletionStage<Void> processSecurityEvent(@ObservesAsync SecurityEvent event) {
        if (SecurityEvent.Type.OIDC_LOGOUT_RP_INITIATED == event.getEventType()) { 
1

	    return revokeTokens(event.getSecurityIdentity()).subscribeAsCompletionStage();
	}
	return CompletableFuture.completedFuture(null);
    }
    private Uni<Void> revokeTokens(SecurityIdentity securityIdentity) {
        return Uni.join().all(
                   revokeAccessToken(securityIdentity),
	           revokeRefreshToken(securityIdentity)
               ).andCollectFailures()
                .replaceWithVoid()
                .onFailure().recoverWithUni(t -> logFailure(t));
    }

    private static Uni<Boolean> revokeAccessToken(SecurityIdentity securityIdentity) { 
2

        OidcProviderClient oidcProvider = securityIdentity.getAttribute(OidcProviderClient.class.getName());
        String accessToken = securityIdentity.getCredential(AccessTokenCredential.class).getToken();
        return oidcProvider.revokeAccessToken(accessToken);
    }

    private static Uni<Boolean> revokeRefreshToken(SecurityIdentity securityIdentity) { 
3

        OidcProviderClient oidcProvider = securityIdentity.getAttribute(OidcProviderClient.class.getName());
        String refreshToken = securityIdentity.getCredential(RefreshToken.class).getToken();
        return oidcProvider.revokeRefreshToken(refreshToken);
    }

    private static Uni<Void> logFailure(Throwable t) {
        // Log failure as required
        return Uni.createFrom().voidItem();
    }
}
Copy to Clipboard Toggle word wrap
1
Revoke tokens if an RP-initiated logout event is observed.
2
Revoke the authorization code flow access token.
3
Revoke the authorization code flow refresh token.

3.2.16. Propagating tokens to downstream services

For information about Authorization Code Flow access token propagation to downstream services, see the Token Propagation section.

3.3. Integration considerations

Your application secured by OIDC integrates in an environment where it can be called from single-page applications. It must work with well-known OIDC providers, run behind HTTP Reverse Proxy, require external and internal access, and so on.

This section discusses these considerations.

3.3.1. Single-page applications

You can check if implementing single-page applications (SPAs) the way it is suggested in the Single-page applications section of the "OpenID Connect (OIDC) Bearer token authentication" guide meets your requirements.

If you prefer to use SPAs and JavaScript APIs such as Fetch or XMLHttpRequest(XHR) with Quarkus web applications, be aware that OIDC providers might not support cross-origin resource sharing (CORS) for authorization endpoints where the users are authenticated after a redirect from Quarkus. This will lead to authentication failures if the Quarkus application and the OIDC provider are hosted on different HTTP domains, ports, or both.

In such cases, set the quarkus.oidc.authentication.java-script-auto-redirect property to false, which will instruct Quarkus to return a 499 status code and a WWW-Authenticate header with the OIDC value.

The browser script must set a header to identify the current request as a JavaScript request for a 499 status code to be returned when the quarkus.oidc.authentication.java-script-auto-redirect property is set to false.

If the script engine sets an engine-specific request header itself, then you can register a custom quarkus.oidc.JavaScriptRequestChecker bean, which will inform Quarkus if the current request is a JavaScript request. For example, if the JavaScript engine sets a header such as HX-Request: true, then you can have it checked like this:

import jakarta.enterprise.context.ApplicationScoped;

import io.quarkus.oidc.JavaScriptRequestChecker;
import io.vertx.ext.web.RoutingContext;

@ApplicationScoped
public class CustomJavaScriptRequestChecker implements JavaScriptRequestChecker {

    @Override
    public boolean isJavaScriptRequest(RoutingContext context) {
        return "true".equals(context.request().getHeader("HX-Request"));
    }
}
Copy to Clipboard Toggle word wrap

and reload the last requested page in case of a 499 status code.

Otherwise, you must also update the browser script to set the X-Requested-With header with the JavaScript value and reload the last requested page in case of a 499 status code.

For example:

Future<void> callQuarkusService() async {
    Map<String, String> headers = Map.fromEntries([MapEntry("X-Requested-With", "JavaScript")]);

    await http
        .get("https://localhost:443/serviceCall")
        .then((response) {
            if (response.statusCode == 499) {
                window.location.assign("https://localhost.com:443/serviceCall");
            }
         });
  }
Copy to Clipboard Toggle word wrap

3.3.2. Cross-origin resource sharing

If you plan to consume this application from a single-page application running on a different domain, you need to configure cross-origin resource sharing (CORS). For more information, see the CORS filter section of the "Cross-origin resource sharing" guide.

The OIDC authentication mechanism can be affected if your Quarkus application is running behind a reverse proxy, gateway, or firewall when HTTP Host header might be reset to the internal IP address and HTTPS connection might be terminated, and so on. For example, an authorization code flow redirect_uri parameter might be set to the internal host instead of the expected external one.

In such cases, configuring Quarkus to recognize the original headers forwarded by the proxy will be required. For more information, see the Running behind a reverse proxy Vert.x documentation section.

For example, if your Quarkus endpoint runs in a cluster behind Kubernetes Ingress, then a redirect from the OIDC provider back to this endpoint might not work because the calculated redirect_uri parameter might point to the internal endpoint address. You can resolve this problem by using the following configuration, where X-ORIGINAL-HOST is set by Kubernetes Ingress to represent the external endpoint address.:

quarkus.http.proxy.proxy-address-forwarding=true
quarkus.http.proxy.allow-forwarded=false
quarkus.http.proxy.enable-forwarded-host=true
quarkus.http.proxy.forwarded-host-header=X-ORIGINAL-HOST
Copy to Clipboard Toggle word wrap

quarkus.oidc.authentication.force-redirect-https-scheme property can also be used when the Quarkus application is running behind an SSL terminating reverse proxy.

The OIDC provider externally-accessible authorization, logout, and other endpoints can have different HTTP(S) URLs compared to the URLs auto-discovered or configured relative to the quarkus.oidc.auth-server-url internal URL. In such cases, the endpoint might report an issuer verification failure and redirects to the externally-accessible OIDC provider endpoints might fail.

If you work with Keycloak, then start it with a KEYCLOAK_FRONTEND_URL system property set to the externally-accessible base URL. If you work with other OIDC providers, check the documentation of your provider.

3.3.5. OIDC HTTP client redirects

OIDC providers behind a firewall may redirect Quarkus OIDC HTTP client’s GET requests to some of its endpoints such as a well-known configuration endpoint. By default, Quarkus OIDC HTTP client follows HTTP redirects automatically, excluding cookies which may have been set during the redirect request for security reasons.

If you would like, you can disable it with quarkus.oidc.follow-redirects=false.

When following redirects automatically is disabled, and Quarkus OIDC HTTP client receives a redirect request, it will attempt to recover only once by following the redirect URI, but only if it is exactly the same as the original request URI, and as long as one or more cookies were set during the redirect request.

3.4. OIDC SAML identity broker

If your identity provider does not implement OpenID Connect but only the legacy XML-based SAML2.0 SSO protocol, then Quarkus cannot be used as a SAML 2.0 adapter, similarly to how quarkus-oidc is used as an OIDC adapter.

However, many OIDC providers such as Keycloak, Okta, Auth0, and Microsoft ADFS offer OIDC to SAML 2.0 bridges. You can create an identity broker connection to a SAML 2.0 provider in your OIDC provider and use quarkus-oidc to authenticate your users to this SAML 2.0 provider, with the OIDC provider coordinating OIDC and SAML 2.0 communications. As far as Quarkus endpoints are concerned, they can continue using the same Quarkus Security, OIDC API, annotations such as @Authenticated, SecurityIdentity, and so on.

For example, assume Okta is your SAML 2.0 provider and Keycloak is your OIDC provider. Here is a typical sequence explaining how to configure Keycloak to broker with the Okta SAML 2.0 provider.

First, create a new SAML2 integration in your Okta Dashboard/Applications:

For example, name it as OktaSaml:

Next, configure it to point to a Keycloak SAML broker endpoint. At this point, you need to know the name of the Keycloak realm, for example, quarkus, and, assuming that the Keycloak SAML broker alias is saml, enter the endpoint address as http://localhost:8081/realms/quarkus/broker/saml/endpoint. Enter the service provider (SP) entity ID as http://localhost:8081/realms/quarkus, where http://localhost:8081 is a Keycloak base address and saml is a broker alias:

Next, save this SAML integration and note its Metadata URL:

Next, add a SAML provider to Keycloak:

First, as usual, create a new realm or import the existing realm to Keycloak. In this case, the realm name has to be quarkus.

Now, in the quarkus realm properties, navigate to Identity Providers and add a new SAML provider:

Note the alias is set to saml, Redirect URI is http://localhost:8081/realms/quarkus/broker/saml/endpoint and Service provider entity ID is http://localhost:8081/realms/quarkus - these are the same values you entered when creating the Okta SAML integration in the previous step.

Finally, set Service entity descriptor to point to the Okta SAML Integration Metadata URL you noted at the end of the previous step.

Next, if you want, you can register this Keycloak SAML provider as a default provider by navigating to Authentication/browser/Identity Provider Redirector config and setting both the Alias and Default Identity Provider properties to saml. If you do not configure it as a default provider then, at authentication time, Keycloak offers 2 options:

  • Authenticate with the SAML provider
  • Authenticate directly to Keycloak with the name and password

Now, configure the Quarkus OIDC web-app application to point to the Keycloak quarkus realm, quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus. Then, you are ready to start authenticating your Quarkus users to the Okta SAML 2.0 provider by using an OIDC to SAML bridge that is provided by Keycloak OIDC and Okta SAML 2.0 providers.

You can configure other OIDC providers to provide a SAML bridge similarly to how it can be done for Keycloak.

3.5. Testing

Testing is often tricky when it comes to authentication to a separate OIDC-like server. Quarkus offers several options from mocking to a local run of an OIDC provider.

Start by adding the following dependencies to your test project:

  • Using Maven:

    <dependency>
        <groupId>org.htmlunit</groupId>
        <artifactId>htmlunit</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>*</artifactId>
           </exclusion>
        </exclusions>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.quarkus</groupId>
        <artifactId>quarkus-junit5</artifactId>
        <scope>test</scope>
    </dependency>
    Copy to Clipboard Toggle word wrap
  • Using Gradle:

    testImplementation("org.htmlunit:htmlunit")
    testImplementation("io.quarkus:quarkus-junit5")
    Copy to Clipboard Toggle word wrap

3.5.1. Dev Services for Keycloak

For integration testing against Keycloak, use Dev services for Keycloak. This service initializes a test container, creates a quarkus realm, and configures a quarkus-app client with the secret secret. It also sets up two users: alice with admin and user roles, and bob with the user role.

First, prepare the application.properties file.

If starting from an empty application.properties file, Dev Services for Keycloak automatically registers the following properties:

  • quarkus.oidc.auth-server-url, which points to the running test container.
  • quarkus.oidc.client-id=quarkus-app.
  • quarkus.oidc.credentials.secret=secret.

If you already have the required quarkus-oidc properties configured, associate quarkus.oidc.auth-server-url with the prod profile. This ensures that Dev Services for Keycloak starts the container as expected. For example:

%prod.quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
Copy to Clipboard Toggle word wrap

To import a custom realm file into Keycloak before running the tests, configure Dev services for Keycloak as shown:

%prod.quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.keycloak.devservices.realm-path=quarkus-realm.json
Copy to Clipboard Toggle word wrap

Finally, write the test code as described in the Wiremock section. The only difference is that @QuarkusTestResource is no longer required:

@QuarkusTest
public class CodeFlowAuthorizationTest {
}
Copy to Clipboard Toggle word wrap

3.5.2. Wiremock

Add the following dependency:

  • Using Maven:

    <dependency>
        <groupId>io.quarkus</groupId>
        <artifactId>quarkus-test-oidc-server</artifactId>
        <scope>test</scope>
    </dependency>
    Copy to Clipboard Toggle word wrap
  • Using Gradle:

    testImplementation("io.quarkus:quarkus-test-oidc-server")
    Copy to Clipboard Toggle word wrap

Prepare the REST test endpoints and set application.properties. For example:

# keycloak.url is set by OidcWiremockTestResource
quarkus.oidc.auth-server-url=${keycloak.url:replaced-by-test-resource}/realms/quarkus/
quarkus.oidc.client-id=quarkus-web-app
quarkus.oidc.credentials.secret=secret
quarkus.oidc.application-type=web-app
Copy to Clipboard Toggle word wrap

Finally, write the test code, for example:

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

import org.htmlunit.SilentCssErrorHandler;
import org.htmlunit.WebClient;
import org.htmlunit.html.HtmlForm;
import org.htmlunit.html.HtmlPage;

import io.quarkus.test.common.QuarkusTestResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.oidc.server.OidcWiremockTestResource;

@QuarkusTest
@QuarkusTestResource(OidcWiremockTestResource.class)
public class CodeFlowAuthorizationTest {

    @Test
    public void testCodeFlow() throws Exception {
        try (final WebClient webClient = createWebClient()) {
            // the test REST endpoint listens on '/code-flow'
            HtmlPage page = webClient.getPage("http://localhost:8081/code-flow");

            HtmlForm form = page.getForms().get(0);
            // user 'alice' has the 'user' role
            form.getInputByName("username").type("alice");
            form.getInputByName("password").type("alice");

            page = form.getButtonByName("login").click();

            assertEquals("alice", page.getBody().asNormalizedText());
        }
    }

    private WebClient createWebClient() {
        WebClient webClient = new WebClient();
        webClient.setCssErrorHandler(new SilentCssErrorHandler());
        return webClient;
    }
}
Copy to Clipboard Toggle word wrap

OidcWiremockTestResource recognizes alice and admin users. The user alice has the user role only by default - it can be customized with a quarkus.test.oidc.token.user-roles system property. The user admin has the user and admin roles by default - it can be customized with a quarkus.test.oidc.token.admin-roles system property.

Additionally, OidcWiremockTestResource sets the token issuer and audience to https://service.example.com, which can be customized with quarkus.test.oidc.token.issuer and quarkus.test.oidc.token.audience system properties.

OidcWiremockTestResource can be used to emulate all OIDC providers.

3.5.3. TestSecurity annotation

You can use @TestSecurity and @OidcSecurity annotations to test the web-app application endpoint code, which depends on either one of the following injections, or all four:

  • ID JsonWebToken
  • Access JsonWebToken
  • UserInfo
  • OidcConfigurationMetadata

For more information, see Use TestingSecurity with injected JsonWebToken.

3.5.4. Checking errors in the logs

To see details about the token verification errors, you must enable io.quarkus.oidc.runtime.OidcProvider TRACE level logging:

quarkus.log.category."io.quarkus.oidc.runtime.OidcProvider".level=TRACE
quarkus.log.category."io.quarkus.oidc.runtime.OidcProvider".min-level=TRACE
Copy to Clipboard Toggle word wrap

To see details about the OidcProvider client initialization errors, enable io.quarkus.oidc.runtime.OidcRecorder TRACE level logging:

quarkus.log.category."io.quarkus.oidc.runtime.OidcRecorder".level=TRACE
quarkus.log.category."io.quarkus.oidc.runtime.OidcRecorder".min-level=TRACE
Copy to Clipboard Toggle word wrap

From the quarkus dev console, type j to change the application global log level.

3.6. Programmatic OIDC start-up

OIDC tenants can be created programmatically like in the example below:

package io.quarkus.it.oidc;

import io.quarkus.oidc.Oidc;
import jakarta.enterprise.event.Observes;

public class OidcStartup {

    void observe(@Observes Oidc oidc) {
        oidc.createWebApp("http://localhost:8180/realms/quarkus", "quarkus-app", "mysecret");
    }

}
Copy to Clipboard Toggle word wrap

The code above is a programmatic equivalent to the following configuration in the application.properties file:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.oidc.application-type=web-app
quarkus.oidc.client-id=quarkus-app
quarkus.oidc.credentials.secret=mysecret
Copy to Clipboard Toggle word wrap

Should you need to configure more OIDC tenant properties, use the OidcTenantConfig builder like in the example below:

package io.quarkus.it.oidc;

import io.quarkus.oidc.Oidc;
import io.quarkus.oidc.OidcTenantConfig;
import io.quarkus.oidc.common.runtime.config.OidcClientCommonConfig.Credentials.Secret.Method;
import jakarta.enterprise.event.Observes;

public class OidcStartup {

    void createDefaultTenant(@Observes Oidc oidc) {
        var defaultTenant = OidcTenantConfig
                .authServerUrl("http://localhost:8180/realms/quarkus/")
                .clientId("quarkus-app")
                .credentials().clientSecret("mysecret", Method.POST).end()
                .build();
        oidc.create(defaultTenant);
    }
}
Copy to Clipboard Toggle word wrap

For more complex setup involving multiple tenants please see the Programmatic OIDC start-up for multitenant application section of the OpenID Connect Multi-Tenancy guide.

3.7. References

Discover how to secure application HTTP endpoints by using the Quarkus OpenID Connect (OIDC) authorization code flow mechanism with the Quarkus OIDC extension, providing robust authentication and authorization.

For more information, see OIDC code flow mechanism for protecting web applications.

To learn about how well-known social providers such as Apple, Facebook, GitHub, Google, Mastodon, Microsoft, Spotify, Twitch, and X (formerly Twitter) can be used with Quarkus OIDC, see Configuring well-known OpenID Connect providers. See also, Authentication mechanisms in Quarkus.

If you want to protect your service applications by using OIDC Bearer token authentication, see OIDC Bearer token authentication.

4.1. Prerequisites

To complete this guide, you need:

  • Roughly 15 minutes
  • An IDE
  • JDK 17+ installed with JAVA_HOME configured appropriately
  • Apache Maven 3.8.6 or later
  • A working container runtime (Docker or Podman)
  • Optionally the Quarkus CLI if you want to use it
  • Optionally Mandrel or GraalVM installed and configured appropriately if you want to build a native executable (or Docker if you use a native container build)

4.2. Architecture

In this example, we build a simple web application with a single page:

  • /index.html

This page is protected, and only authenticated users can access it.

4.3. Solution

Follow the instructions in the next sections and create the application step by step. Alternatively, you can go right to the completed example.

Clone the Git repository by running the git clone https://github.com/quarkusio/quarkus-quickstarts.git -b 3.20 command. Alternatively, download an archive.

The solution is located in the security-openid-connect-web-authentication-quickstart directory.

4.4. Create the Maven project

First, we need a new project. Create a new project by running the following command:

  • Using the Quarkus CLI:

    quarkus create app org.acme:security-openid-connect-web-authentication-quickstart \
        --extension='rest,oidc' \
        --no-code
    cd security-openid-connect-web-authentication-quickstart
    Copy to Clipboard Toggle word wrap

    To create a Gradle project, add the --gradle or --gradle-kotlin-dsl option.

    For more information about how to install and use the Quarkus CLI, see the Quarkus CLI guide.

  • Using Maven:

    mvn com.redhat.quarkus.platform:quarkus-maven-plugin:3.20.1:create \
        -DprojectGroupId=org.acme \
        -DprojectArtifactId=security-openid-connect-web-authentication-quickstart \
        -Dextensions='rest,oidc' \
        -DnoCode
    cd security-openid-connect-web-authentication-quickstart
    Copy to Clipboard Toggle word wrap

    To create a Gradle project, add the -DbuildTool=gradle or -DbuildTool=gradle-kotlin-dsl option.

For Windows users:

  • If using cmd, (don’t use backward slash \ and put everything on the same line)
  • If using Powershell, wrap -D parameters in double quotes e.g. "-DprojectArtifactId=security-openid-connect-web-authentication-quickstart"

If you already have your Quarkus project configured, you can add the oidc extension to your project by running the following command in your project base directory:

  • Using the Quarkus CLI:

    quarkus extension add oidc
    Copy to Clipboard Toggle word wrap
  • Using Maven:

    ./mvnw quarkus:add-extension -Dextensions='oidc'
    Copy to Clipboard Toggle word wrap
  • Using Gradle:

    ./gradlew addExtension --extensions='oidc'
    Copy to Clipboard Toggle word wrap

This adds the following dependency to your build file:

  • Using Maven:

    <dependency>
       <groupId>io.quarkus</groupId>
       <artifactId>quarkus-oidc</artifactId>
    </dependency>
    Copy to Clipboard Toggle word wrap
  • Using Gradle:

    implementation("io.quarkus:quarkus-oidc")
    Copy to Clipboard Toggle word wrap

4.5. Write the application

Let’s write a simple Jakarta REST resource that has all the tokens returned in the authorization code grant response injected:

package org.acme.security.openid.connect.web.authentication;

import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;

import org.eclipse.microprofile.jwt.Claims;
import org.eclipse.microprofile.jwt.JsonWebToken;

import io.quarkus.oidc.IdToken;
import io.quarkus.oidc.RefreshToken;

@Path("/tokens")
public class TokenResource {

   /**
    * Injection point for the ID token issued by the OpenID Connect provider
    */
   @Inject
   @IdToken
   JsonWebToken idToken;

   /**
    * Injection point for the access token issued by the OpenID Connect provider
    */
   @Inject
   JsonWebToken accessToken;

   /**
    * Injection point for the refresh token issued by the OpenID Connect provider
    */
   @Inject
   RefreshToken refreshToken;

   /**
    * Returns the tokens available to the application.
    * This endpoint exists only for demonstration purposes.
    * Do not expose these tokens in a real application.
    *
    * @return an HTML page containing the tokens available to the application.
    */
   @GET
   @Produces("text/html")
   public String getTokens() {
       StringBuilder response = new StringBuilder().append("<html>")
               .append("<body>")
               .append("<ul>");


       Object userName = this.idToken.getClaim(Claims.preferred_username);

       if (userName != null) {
           response.append("<li>username: ").append(userName.toString()).append("</li>");
       }

       Object scopes = this.accessToken.getClaim("scope");

       if (scopes != null) {
           response.append("<li>scopes: ").append(scopes.toString()).append("</li>");
       }

       response.append("<li>refresh_token: ").append(refreshToken.getToken() != null).append("</li>");

       return response.append("</ul>").append("</body>").append("</html>").toString();
   }
}
Copy to Clipboard Toggle word wrap

This endpoint has ID, access, and refresh tokens injected. It returns a preferred_username claim from the ID token, a scope claim from the access token, and a refresh token availability status.

You only need to inject the tokens if the endpoint needs to use the ID token to interact with the currently authenticated user or use the access token to access a downstream service on behalf of this user.

For more information, see the Access ID and Access Tokens section of the reference guide.

4.6. Configure the application

The OIDC extension allows you to define the configuration by using the application.properties file in the src/main/resources directory.

%prod.quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.oidc.client-id=frontend
quarkus.oidc.credentials.secret=secret
quarkus.oidc.application-type=web-app
quarkus.http.auth.permission.authenticated.paths=/*
quarkus.http.auth.permission.authenticated.policy=authenticated
Copy to Clipboard Toggle word wrap

This is the simplest configuration you can have when enabling authentication to your application.

The quarkus.oidc.client-id property references the client_id issued by the OIDC provider, and the quarkus.oidc.credentials.secret property sets the client secret.

The quarkus.oidc.application-type property is set to web-app to tell Quarkus that you want to enable the OIDC authorization code flow so that your users are redirected to the OIDC provider to authenticate.

Finally, the quarkus.http.auth.permission.authenticated permission is set to tell Quarkus about the paths you want to protect. In this case, all paths are protected by a policy that ensures only authenticated users can access them. For more information, see Security Authorization Guide.

Note

When you do not configure a client secret with quarkus.oidc.credentials.secret, it is recommended to configure quarkus.oidc.token-state-manager.encryption-secret.

The quarkus.oidc.token-state-manager.encryption-secret enables the default token state manager to encrypt the user tokens in a browser cookie. If this key is not defined, and the quarkus.oidc.credentials.secret fallback is not configured, Quarkus uses a random key. A random key causes existing logins to be invalidated either on application restart or in environment with multiple instances of your application. Alternatively, encryption can also be disabled by setting quarkus.oidc.token-state-manager.encryption-required to false. However, you should disable secret encryption in development environments only.

The encryption secret is recommended to be 32 chars long. For example, quarkus.oidc.token-state-manager.encryption-secret=AyM1SysPpbyDfgZld3umj1qzKObwVMk

4.7. Start and configure the Keycloak server

To start a Keycloak server, use Docker and run the following command:

docker run --name keycloak -e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin -p 8180:8080 quay.io/keycloak/keycloak:{keycloak.version} start-dev
Copy to Clipboard Toggle word wrap

where keycloak.version is set to 26.1.3 or later.

You can access your Keycloak Server at localhost:8180.

To access the Keycloak Administration Console, log in as the admin user. The username and password are both admin.

To create a new realm, import the realm configuration file. For more information, see the Keycloak documentation about how to create and configure a new realm.

4.8. Run the application in dev and JVM modes

To run the application in dev mode, use:

  • Using the Quarkus CLI:

    quarkus dev
    Copy to Clipboard Toggle word wrap
  • Using Maven:

    ./mvnw quarkus:dev
    Copy to Clipboard Toggle word wrap
  • Using Gradle:

    ./gradlew --console=plain quarkusDev
    Copy to Clipboard Toggle word wrap

After exploring the application in dev mode, you can run it as a standard Java application.

First, compile it:

  • Using the Quarkus CLI:

    quarkus build
    Copy to Clipboard Toggle word wrap
  • Using Maven:

    ./mvnw install
    Copy to Clipboard Toggle word wrap
  • Using Gradle:

    ./gradlew build
    Copy to Clipboard Toggle word wrap

Then, run it:

java -jar target/quarkus-app/quarkus-run.jar
Copy to Clipboard Toggle word wrap

4.9. Run the application in Native mode

This same demo can be compiled into native code. No modifications are required.

This implies that you no longer need to install a JVM on your production environment, as the runtime technology is included in the produced binary and optimized to run with minimal resources.

Compilation takes longer, so this step is turned off by default. You can build again by enabling the native build:

  • Using the Quarkus CLI:

    quarkus build --native
    Copy to Clipboard Toggle word wrap
  • Using Maven:

    ./mvnw install -Dnative
    Copy to Clipboard Toggle word wrap
  • Using Gradle:

    ./gradlew build -Dquarkus.native.enabled=true
    Copy to Clipboard Toggle word wrap

After a while, you can run this binary directly:

./target/security-openid-connect-web-authentication-quickstart-runner
Copy to Clipboard Toggle word wrap

4.10. Test the application

To test the application, open your browser and access the following URL:

If everything works as expected, you are redirected to the Keycloak server to authenticate.

To authenticate to the application, enter the following credentials at the Keycloak login page:

  • Username: alice
  • Password: alice

After clicking the Login button, you are redirected back to the application, and a session cookie will be created.

The session for this demo is valid for a short period of time and, on every page refresh, you will be asked to re-authenticate. For information about how to increase the session timeouts, see the Keycloak session timeout documentation. For example, you can access the Keycloak Admin console directly from the dev UI by clicking the Keycloak Admin link if you use Dev Services for Keycloak in dev mode:

For more information about writing the integration tests that depend on Dev Services for Keycloak, see the Dev Services for Keycloak section.

4.11. Summary

You have learned how to set up and use the OIDC authorization code flow mechanism to protect and test application HTTP endpoints. After you have completed this tutorial, explore OIDC Bearer token authentication and other authentication mechanisms.

4.12. References

This guide demonstrates how your OpenID Connect (OIDC) application can support multitenancy to serve multiple tenants from a single application. These tenants can be distinct realms or security domains within the same OIDC provider or even distinct OIDC providers.

Each customer functions as a distinct tenant when serving multiple customers from the same application, such as in a SaaS environment. By enabling multitenancy support to your applications, you can support distinct authentication policies for each tenant, even authenticating against different OIDC providers, such as Keycloak and Google.

To authorize a tenant by using Bearer Token Authorization, see the OpenID Connect (OIDC) Bearer token authentication guide.

To authenticate and authorize a tenant by using the OIDC authorization code flow, read the OpenID Connect authorization code flow mechanism for protecting web applications guide.

Also, see the OpenID Connect (OIDC) configuration properties reference guide.

5.1. Prerequisites

To complete this guide, you need:

  • Roughly 15 minutes
  • An IDE
  • JDK 17+ installed with JAVA_HOME configured appropriately
  • Apache Maven 3.8.6 or later
  • A working container runtime (Docker or Podman)
  • Optionally the Quarkus CLI if you want to use it
  • Optionally Mandrel or GraalVM installed and configured appropriately if you want to build a native executable (or Docker if you use a native container build)
  • jq tool

5.2. Architecture

In this example, we build a very simple application that supports two resource methods:

  • /{tenant}

This resource returns information obtained from the ID token issued by the OIDC provider about the authenticated user and the current tenant.

  • /{tenant}/bearer

This resource returns information obtained from the Access Token issued by the OIDC provider about the authenticated user and the current tenant.

5.3. Solution

For a thorough understanding, we recommend you build the application by following the upcoming step-by-step instructions.

Alternatively, if you prefer to start with the completed example, clone the Git repository: git clone https://github.com/quarkusio/quarkus-quickstarts.git -b 3.20, or download an archive.

The solution is located in the security-openid-connect-multi-tenancy-quickstart directory.

5.4. Creating the Maven project

First, we need a new project. Create a new project with the following command:

  • Using the Quarkus CLI:

    quarkus create app org.acme:security-openid-connect-multi-tenancy-quickstart \
        --extension='oidc,rest-jackson' \
        --no-code
    cd security-openid-connect-multi-tenancy-quickstart
    Copy to Clipboard Toggle word wrap

    To create a Gradle project, add the --gradle or --gradle-kotlin-dsl option.

    For more information about how to install and use the Quarkus CLI, see the Quarkus CLI guide.

  • Using Maven:

    mvn com.redhat.quarkus.platform:quarkus-maven-plugin:3.20.1:create \
        -DprojectGroupId=org.acme \
        -DprojectArtifactId=security-openid-connect-multi-tenancy-quickstart \
        -Dextensions='oidc,rest-jackson' \
        -DnoCode
    cd security-openid-connect-multi-tenancy-quickstart
    Copy to Clipboard Toggle word wrap

    To create a Gradle project, add the -DbuildTool=gradle or -DbuildTool=gradle-kotlin-dsl option.

For Windows users:

  • If using cmd, (don’t use backward slash \ and put everything on the same line)
  • If using Powershell, wrap -D parameters in double quotes e.g. "-DprojectArtifactId=security-openid-connect-multi-tenancy-quickstart"

If you already have your Quarkus project configured, add the oidc extension to your project by running the following command in your project base directory:

  • Using the Quarkus CLI:

    quarkus extension add oidc
    Copy to Clipboard Toggle word wrap
  • Using Maven:

    ./mvnw quarkus:add-extension -Dextensions='oidc'
    Copy to Clipboard Toggle word wrap
  • Using Gradle:

    ./gradlew addExtension --extensions='oidc'
    Copy to Clipboard Toggle word wrap

This adds the following to your build file:

  • Using Maven:

    <dependency>
        <groupId>io.quarkus</groupId>
        <artifactId>quarkus-oidc</artifactId>
    </dependency>
    Copy to Clipboard Toggle word wrap
  • Using Gradle:

    implementation("io.quarkus:quarkus-oidc")
    Copy to Clipboard Toggle word wrap

5.5. Writing the application

Start by implementing the /{tenant} endpoint. As you can see from the source code below, it is just a regular Jakarta REST resource:

package org.acme.quickstart.oidc;

import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;

import org.eclipse.microprofile.jwt.JsonWebToken;

import io.quarkus.oidc.IdToken;

@Path("/{tenant}")
public class HomeResource {
    /**
     * Injection point for the ID Token issued by the OIDC provider.
     */
    @Inject
    @IdToken
    JsonWebToken idToken;

    /**
     * Injection point for the Access Token issued by the OIDC provider.
     */
    @Inject
    JsonWebToken accessToken;

    /**
     * Returns the ID Token info.
     * This endpoint exists only for demonstration purposes.
     * Do not expose this token in a real application.
     *
     * @return ID Token info
     */
    @GET
    @Produces("text/html")
    public String getIdTokenInfo() {
        StringBuilder response = new StringBuilder().append("<html>")
                .append("<body>");

        response.append("<h2>Welcome, ").append(this.idToken.getClaim("email").toString()).append("</h2>\n");
        response.append("<h3>You are accessing the application within tenant <b>").append(idToken.getIssuer()).append(" boundaries</b></h3>");

        return response.append("</body>").append("</html>").toString();
    }

    /**
     * Returns the Access Token info.
     * This endpoint exists only for demonstration purposes.
     * Do not expose this token in a real application.
     *
     * @return Access Token info
     */
    @GET
    @Produces("text/html")
    @Path("bearer")
    public String getAccessTokenInfo() {
        StringBuilder response = new StringBuilder().append("<html>")
                .append("<body>");

        response.append("<h2>Welcome, ").append(this.accessToken.getClaim("email").toString()).append("</h2>\n");
        response.append("<h3>You are accessing the application within tenant <b>").append(accessToken.getIssuer()).append(" boundaries</b></h3>");

        return response.append("</body>").append("</html>").toString();
    }
}
Copy to Clipboard Toggle word wrap

To resolve the tenant from incoming requests and map it to a specific quarkus-oidc tenant configuration in application.properties, create an implementation for the io.quarkus.oidc.TenantConfigResolver interface, which can dynamically resolve tenant configurations:

package org.acme.quickstart.oidc;

import jakarta.enterprise.context.ApplicationScoped;

import org.eclipse.microprofile.config.ConfigProvider;

import io.quarkus.oidc.OidcRequestContext;
import io.quarkus.oidc.OidcTenantConfig;
import io.quarkus.oidc.OidcTenantConfig.ApplicationType;
import io.quarkus.oidc.TenantConfigResolver;
import io.quarkus.oidc.runtime.OidcUtils;
import io.smallrye.mutiny.Uni;
import io.vertx.ext.web.RoutingContext;

@ApplicationScoped
public class CustomTenantResolver implements TenantConfigResolver {

    @Override
    public Uni<OidcTenantConfig> resolve(RoutingContext context, OidcRequestContext<OidcTenantConfig> requestContext) {
        String path = context.request().path();

        if (path.startsWith("/tenant-a")) {
           String keycloakUrl = ConfigProvider.getConfig().getValue("keycloak.url", String.class);

            OidcTenantConfig config = OidcTenantConfig
                    .authServerUrl(keycloakUrl + "/realms/tenant-a")
                    .tenantId("tenant-a")
                    .clientId("multi-tenant-client")
                    .credentials("secret")
                    .applicationType(ApplicationType.HYBRID)
                    .build();
            return Uni.createFrom().item(config);
        } else {
            // resolve to default tenant config
            return Uni.createFrom().nullItem();
        }
    }
}
Copy to Clipboard Toggle word wrap

In the preceding implementation, tenants are resolved from the request path. If no tenant can be inferred, null is returned to indicate that the default tenant configuration should be used.

The tenant-a application type is hybrid; it can accept HTTP bearer tokens if provided. Otherwise, it initiates an authorization code flow when authentication is required.

5.6. Configuring the application

# Default tenant configuration
%prod.quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.oidc.client-id=multi-tenant-client
quarkus.oidc.credentials.secret=secret
quarkus.oidc.application-type=web-app

# Tenant A configuration is created dynamically in CustomTenantConfigResolver

# HTTP security configuration
quarkus.http.auth.permission.authenticated.paths=/*
quarkus.http.auth.permission.authenticated.policy=authenticated
Copy to Clipboard Toggle word wrap

The first configuration is the default tenant configuration that should be used when the tenant cannot be inferred from the request. Be aware that a %prod profile prefix is used with quarkus.oidc.auth-server-url to support testing a multitenant application with Dev Services For Keycloak. This configuration uses a Keycloak instance to authenticate users.

The second configuration, provided by TenantConfigResolver, is used when an incoming request is mapped to the tenant-a tenant.

Both configurations map to the same Keycloak server instance while using distinct realms.

Alternatively, you can configure the tenant tenant-a directly in application.properties:

# Default tenant configuration
%prod.quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.oidc.client-id=multi-tenant-client
quarkus.oidc.credentials.secret=secret
quarkus.oidc.application-type=web-app

# Tenant A configuration
quarkus.oidc.tenant-a.auth-server-url=http://localhost:8180/realms/tenant-a
quarkus.oidc.tenant-a.client-id=multi-tenant-client
quarkus.oidc.tenant-a.credentials.secret=secret
quarkus.oidc.tenant-a.application-type=web-app

# HTTP security configuration
quarkus.http.auth.permission.authenticated.paths=/*
quarkus.http.auth.permission.authenticated.policy=authenticated
Copy to Clipboard Toggle word wrap

In that case, also use a custom TenantConfigResolver to resolve it:

package org.acme.quickstart.oidc;

import jakarta.enterprise.context.ApplicationScoped;

import io.quarkus.oidc.TenantResolver;
import io.vertx.ext.web.RoutingContext;

@ApplicationScoped
public class CustomTenantResolver implements TenantResolver {

    @Override
    public String resolve(RoutingContext context) {
        String path = context.request().path();
        String[] parts = path.split("/");

        if (parts.length == 0) {
            //Resolve to default tenant configuration
            return null;
        }

        return parts[1];
    }
}
Copy to Clipboard Toggle word wrap

You can define multiple tenants in your configuration file. To map them correctly when resolving a tenant from your TenantResolver implementation, ensure each has a unique alias.

However, using a static tenant resolution, which involves configuring tenants in application.properties and resolving them with TenantResolver, does not work for testing endpoints with Dev Services for Keycloak because it does not know how the requests are be mapped to individual tenants, and cannot dynamically provide tenant-specific quarkus.oidc.<tenant-id>.auth-server-url values. Therefore, using %prod prefixes with tenant-specific URLs within application.properties does not work in both test and development modes.

Note

When a current tenant represents an OIDC web-app application, the current io.vertx.ext.web.RoutingContext contains a tenant-id attribute by the time the custom tenant resolver has been called for all the requests completing the code authentication flow and the already authenticated requests, when either a tenant-specific state or session cookie already exists. Therefore, when working with multiple OIDC providers, you only need a path-specific check to resolve a tenant id if the RoutingContext does not have the tenant-id attribute set, for example:

package org.acme.quickstart.oidc;

import jakarta.enterprise.context.ApplicationScoped;

import io.quarkus.oidc.TenantResolver;
import io.vertx.ext.web.RoutingContext;

@ApplicationScoped
public class CustomTenantResolver implements TenantResolver {

    @Override
    public String resolve(RoutingContext context) {
        String tenantId = context.get("tenant-id");
        if (tenantId != null) {
            return tenantId;
        } else {
            // Initial login request
            String path = context.request().path();
            String[] parts = path.split("/");

            if (parts.length == 0) {
                //Resolve to default tenant configuration
                return null;
            }
            return parts[1];
        }
    }
}
Copy to Clipboard Toggle word wrap

This is how Quarkus OIDC resolves static custom tenants if no custom TenantResolver is registered.

A similar technique can be used with TenantConfigResolver, where a tenant-id provided in the context can return OidcTenantConfig already prepared with the previous request.

Note

If you also use Hibernate ORM multitenancy or MongoDB with Panache multitenancy and both tenant ids are the same, you can get the tenant id from the RoutingContext attribute with tenant-id. You can find more information here:

5.7. Starting and configuring the Keycloak server

To start a Keycloak server, you can use Docker and run the following command:

docker run --name keycloak -e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin -p 8180:8080 quay.io/keycloak/keycloak:{keycloak.version} start-dev
Copy to Clipboard Toggle word wrap

where keycloak.version is set to 26.0.7 or higher.

Access your Keycloak server at localhost:8180.

Log in as the admin user to access the Keycloak administration console. The username and password are both admin.

Now, import the realms for the two tenants:

For more information, see the Keycloak documentation about how to create a new realm.

5.8. Running and using the application

5.8.1. Running in developer mode

To run the microservice in dev mode, use:

  • Using the Quarkus CLI:

    quarkus dev
    Copy to Clipboard Toggle word wrap
  • Using Maven:

    ./mvnw quarkus:dev
    Copy to Clipboard Toggle word wrap
  • Using Gradle:

    ./gradlew --console=plain quarkusDev
    Copy to Clipboard Toggle word wrap

5.8.2. Running in JVM mode

After exploring the application in dev mode, you can run it as a standard Java application.

First, compile it:

  • Using the Quarkus CLI:

    quarkus build
    Copy to Clipboard Toggle word wrap
  • Using Maven:

    ./mvnw install
    Copy to Clipboard Toggle word wrap
  • Using Gradle:

    ./gradlew build
    Copy to Clipboard Toggle word wrap

Then run it:

java -jar target/quarkus-app/quarkus-run.jar
Copy to Clipboard Toggle word wrap

5.8.3. Running in native mode

This same demo can be compiled into native code; no modifications are required.

This implies that you no longer need to install a JVM on your production environment, as the runtime technology is included in the produced binary, and optimized to run with minimal resources.

Compilation takes a bit longer, so this step is turned off by default; let’s build again by enabling the native build:

  • Using the Quarkus CLI:

    quarkus build --native
    Copy to Clipboard Toggle word wrap
  • Using Maven:

    ./mvnw install -Dnative
    Copy to Clipboard Toggle word wrap
  • Using Gradle:

    ./gradlew build -Dquarkus.native.enabled=true
    Copy to Clipboard Toggle word wrap

After a little while, you can run this binary directly:

./target/security-openid-connect-multi-tenancy-quickstart-runner
Copy to Clipboard Toggle word wrap

5.9. Test the application

5.9.1. Use the browser

To test the application, open your browser and access the following URL:

If everything works as expected, you are redirected to the Keycloak server to authenticate. Be aware that the requested path defines a default tenant, which we don’t have mapped in the configuration file. In this case, the default configuration is used.

To authenticate to the application, enter the following credentials in the Keycloak login page:

  • Username: alice
  • Password: alice

After clicking the Login button, you are redirected back to the application.

If you try now to access the application at the following URL:

You are redirected again to the Keycloak login page. However, this time, you are going to authenticate by using a different realm.

In both cases, the landing page shows the user’s name and email if the user is successfully authenticated. Although alice exists in both tenants, the application treats them as distinct users in separate realms.

5.10. Tenant resolution

5.10.1. Tenant resolution order

OIDC tenants are resolved in the following order:

  1. io.quarkus.oidc.Tenant annotation is checked first if the proactive authentication is disabled.
  2. Dynamic tenant resolution using a custom TenantConfigResolver.
  3. Static tenant resolution using one of these options: custom TenantResolver, configured tenant paths, and defaulting to the last request path segment as a tenant id.

Finally, the default OIDC tenant is selected if a tenant id has not been resolved after the preceding steps.

See the following sections for more information:

Additionally, for the OIDC web-app applications, the state and session cookies also provide a hint about the tenant resolved with one of the above mentioned options at the time when the authorization code flow started. See the Tenant resolution for OIDC web-app applications section for more information.

5.10.2. Resolve with annotations

You can use the io.quarkus.oidc.Tenant annotation for resolving the tenant identifiers as an alternative to using io.quarkus.oidc.TenantResolver.

Note

Proactive HTTP authentication must be disabled (quarkus.http.auth.proactive=false) for this to work. For more information, see the Proactive authentication guide.

Assuming your application supports two OIDC tenants, the hr and default tenants, all resource methods and classes carrying @Tenant("hr") are authenticated by using the OIDC provider configured by quarkus.oidc.hr.auth-server-url. In contrast, all other classes and methods are still authenticated by using the default OIDC provider.

import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;

import io.quarkus.oidc.Tenant;
import io.quarkus.security.Authenticated;

@Authenticated
@Path("/api/hello")
public class HelloResource {

    @Tenant("hr") 
1

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String sayHello() {
        return "Hello!";
    }
}
Copy to Clipboard Toggle word wrap
1
The io.quarkus.oidc.Tenant annotation must be placed on either the resource class or resource method.
Tip

In the example above, authentication of the sayHello endpoint is enforced with the @Authenticated annotation.

Alternatively, if you use an the HTTP Security policy to secure the endpoint, then, for the @Tenant annotation be effective, you must delay this policy’s permission check as shown in the following example:

quarkus.http.auth.permission.authenticated.paths=/api/hello
quarkus.http.auth.permission.authenticated.methods=GET
quarkus.http.auth.permission.authenticated.policy=authenticated
quarkus.http.auth.permission.authenticated.applies-to=JAXRS 
1
Copy to Clipboard Toggle word wrap
1
Tell Quarkus to run the HTTP permission check after the tenant has been selected with the @Tenant annotation.

5.10.3. Dynamic tenant configuration resolution

If you need a more dynamic configuration for the different tenants you want to support and don’t want to end up with multiple entries in your configuration file, you can use the io.quarkus.oidc.TenantConfigResolver.

This interface allows you to dynamically create tenant configurations at runtime:

package io.quarkus.it.keycloak;

import jakarta.enterprise.context.ApplicationScoped;
import java.util.function.Supplier;

import io.smallrye.mutiny.Uni;
import io.quarkus.oidc.OidcRequestContext;
import io.quarkus.oidc.OidcTenantConfig;
import io.quarkus.oidc.TenantConfigResolver;
import io.vertx.ext.web.RoutingContext;

@ApplicationScoped
public class CustomTenantConfigResolver implements TenantConfigResolver {

    @Override
    public Uni<OidcTenantConfig> resolve(RoutingContext context, OidcRequestContext<OidcTenantConfig> requestContext) {
        String path = context.request().path();
        String[] parts = path.split("/");

        if (parts.length == 0) {
            //Resolve to default tenant configuration
            return null;
        }

        if ("tenant-c".equals(parts[1])) {
            // Do 'return requestContext.runBlocking(createTenantConfig());'
            // if a blocking call is required to create a tenant config,
            return Uni.createFrom().item(createTenantConfig());
        }

        //Resolve to default tenant configuration
        return null;
    }

    private Supplier<OidcTenantConfig> createTenantConfig() {
        final OidcTenantConfig config = OidcTenantConfig
                .authServerUrl("http://localhost:8180/realms/tenant-c")
                .tenantId("tenant-c")
                .clientId("multi-tenant-client")
                .credentials("my-secret")
                .build();

        // Any other setting supported by the quarkus-oidc extension

        return () -> config;
    }
}
Copy to Clipboard Toggle word wrap

The OidcTenantConfig returned by this method is the same one used to parse the oidc namespace configuration from the application.properties. You can populate it by using any settings supported by the quarkus-oidc extension.

If the dynamic tenant resolver returns null, a Static tenant configuration resolution is attempted next.

5.10.4. Static tenant configuration resolution

When you set multiple tenant configurations in the application.properties file, you only need to specify how the tenant identifier gets resolved. To configure the resolution of the tenant identifier, use one of the following options:

These tenant resolution options are tried in the order they are listed until the tenant id gets resolved. If the tenant id remains unresolved (null), the default (unnamed) tenant configuration is selected.

5.10.4.1. Resolve with TenantResolver

The following application.properties example shows how you can resolve the tenant identifier of two tenants named a and b by using the TenantResolver method:

# Tenant 'a' configuration
quarkus.oidc.a.auth-server-url=http://localhost:8180/realms/quarkus-a
quarkus.oidc.a.client-id=client-a
quarkus.oidc.a.credentials.secret=client-a-secret

# Tenant 'b' configuration
quarkus.oidc.b.auth-server-url=http://localhost:8180/realms/quarkus-b
quarkus.oidc.b.client-id=client-b
quarkus.oidc.b.credentials.secret=client-b-secret
Copy to Clipboard Toggle word wrap

You can return the tenant id of either a or b from io.quarkus.oidc.TenantResolver:

import io.quarkus.oidc.TenantResolver;
import io.vertx.ext.web.RoutingContext;

public class CustomTenantResolver implements TenantResolver {

    @Override
    public String resolve(RoutingContext context) {
        String path = context.request().path();
        if (path.endsWith("a")) {
            return "a";
        } else if (path.endsWith("b")) {
            return "b";
        } else {
            // default tenant
            return null;
        }
    }
}
Copy to Clipboard Toggle word wrap

In this example, the value of the last request path segment is a tenant id, but if required, you can implement a more complex tenant identifier resolution logic.

5.10.4.2. Configure tenant paths

You can use the quarkus.oidc.tenant-paths configuration property for resolving the tenant identifier as an alternative to using io.quarkus.oidc.TenantResolver. Here is how you can select the hr tenant for the sayHello endpoint of the HelloResource resource used in the previous example:

quarkus.oidc.hr.tenant-paths=/api/hello 
1

quarkus.oidc.a.tenant-paths=/api/* 
2

quarkus.oidc.b.tenant-paths=/*/hello 
3
Copy to Clipboard Toggle word wrap
1
Same path-matching rules apply as for the quarkus.http.auth.permission.authenticated.paths=/api/hello configuration property from the previous example.
2
The wildcard placed at the end of the path represents any number of path segments. However the path is less specific than the /api/hello, therefore the hr tenant will be used to secure the sayHello endpoint.
3
The wildcard in the /*/hello represents exactly one path segment. Nevertheless, the wildcard is less specific than the api, therefore the hr tenant will be used.
Tip

Path-matching mechanism works exactly same as in the Authorization using configuration.

The default resolution for a tenant identifier is convention based, whereby the authentication request must include the tenant identifier in the last segment of the request path.

The following application.properties example shows how you can configure two tenants named google and github:

# Tenant 'google' configuration
quarkus.oidc.google.provider=google
quarkus.oidc.google.client-id=${google-client-id}
quarkus.oidc.google.credentials.secret=${google-client-secret}
quarkus.oidc.google.authentication.redirect-path=/signed-in

# Tenant 'github' configuration
quarkus.oidc.github.provider=github
quarkus.oidc.github.client-id=${github-client-id}
quarkus.oidc.github.credentials.secret=${github-client-secret}
quarkus.oidc.github.authentication.redirect-path=/signed-in
Copy to Clipboard Toggle word wrap

In the provided example, both tenants configure OIDC web-app applications to use an authorization code flow to authenticate users and require session cookies to be generated after authentication. After Google or GitHub authenticates the current user, the user gets returned to the /signed-in area for authenticated users, such as a secured resource path on the JAX-RS endpoint.

Finally, to complete the default tenant resolution, set the following configuration property:

quarkus.http.auth.permission.login.paths=/google,/github
quarkus.http.auth.permission.login.policy=authenticated
Copy to Clipboard Toggle word wrap

If the endpoint is running on http://localhost:8080, you can also provide UI options for users to log in to either http://localhost:8080/google or http://localhost:8080/github, without having to add specific /google or /github JAX-RS resource paths. Tenant identifiers are also recorded in the session cookie names after the authentication is completed. Therefore, authenticated users can access the secured application area without requiring either the google or github path values to be included in the secured URL.

Default resolution can also work for Bearer token authentication. Still, it might be less practical because a tenant identifier must always be set as the last path segment value.

OIDC tenants which support Bearer token authentication can be resolved using the access token’s issuer. The following conditions must be met for the issuer-based resolution to work:

  • The access token must be in the JWT format and contain an issuer (iss) token claim.
  • Only OIDC tenants with the application type service or hybrid are considered. These tenants must have a token issuer discovered or configured.

The issuer-based resolution is enabled with the quarkus.oidc.resolve-tenants-with-issuer property. For example:

quarkus.oidc.resolve-tenants-with-issuer=true 
1


quarkus.oidc.tenant-a.auth-server-url=${tenant-a-oidc-provider} 
2

quarkus.oidc.tenant-a.client-id=${tenant-a-client-id}
quarkus.oidc.tenant-a.credentials.secret=${tenant-a-client-secret}

quarkus.oidc.tenant-b.auth-server-url=${tenant-b-oidc-provider} 
3

quarkus.oidc.tenant-b.discover-enabled=false
quarkus.oidc.tenant-b.token.issuer=${tenant-b-oidc-provider}/issuer
quarkus.oidc.tenant-b.jwks-path=/jwks
quarkus.oidc.tenant-b.token-path=/tokens
quarkus.oidc.tenant-b.client-id=${tenant-b-client-id}
quarkus.oidc.tenant-b.credentials.secret=${tenant-b-client-secret}
Copy to Clipboard Toggle word wrap
1
Tenants tenant-a and tenant-b are resolved using a JWT access token’s issuer iss claim value.
2
Tenant tenant-a discovers the issuer from the OIDC provider’s well-known configuration endpoint.
3
Tenant tenant-b configures the issuer because its OIDC provider does not support the discovery.

Tenant resolution for the OIDC web-app applications must be done at least 3 times during an authorization code flow, when the OIDC tenant-specific configuration affects how each of the following steps is run.

Step 1: Unauthenticated user accesses an endpoint and is redirected to OIDC provider

When an unauthenticated user accesses a secured path, the user is redirected to the OIDC provider to authenticate and the tenant configuration is used to build the redirect URI.

All the static and dynamic tenant resolution options listed in the Static tenant configuration resolution and Dynamic tenant configuration resolution sections can be used to resolve a tenant.

Step 2: The user is redirected back to the endpoint

After the provider authentication, the user is redirected back to the Quarkus endpoint and the tenant configuration is used to complete the authorization code flow.

All the static and dynamic tenant resolution options listed in the Static tenant configuration resolution and Dynamic tenant configuration resolution sections can be used to resolve a tenant. Before the tenant resolution begins, the authorization code flow state cookie is used to set the already resolved tenant configuration id as a RoutingContext tenant-id attribute: both custom dynamic TenantConfigResolver and static TenantResolver tenant resolvers can check it.

Step 3: Authenticated user accesses the secured path using the session cookie

The tenant configuration determines how the session cookie is verified and refreshed. Before the tenant resolution begins, the authorization code flow session cookie is used to set the already resolved tenant configuration id as a RoutingContext tenant-id attribute: both custom dynamic TenantConfigResolver and static TenantResolver tenant resolvers can check it.

For example, here is how a custom TenantConfigResolver can avoid creating the already resolved tenant configuration, that may otherwise require blocking reads from the database or other remote sources:

package io.quarkus.it.keycloak;

import jakarta.enterprise.context.ApplicationScoped;
import io.quarkus.oidc.OidcRequestContext;
import io.quarkus.oidc.OidcTenantConfig;
import io.quarkus.oidc.OidcTenantConfig.ApplicationType;
import io.quarkus.oidc.TenantConfigResolver;
import io.quarkus.oidc.runtime.OidcUtils;
import io.smallrye.mutiny.Uni;
import io.vertx.ext.web.RoutingContext;

@ApplicationScoped
public class CustomTenantConfigResolver implements TenantConfigResolver {

    @Override
    public Uni<OidcTenantConfig> resolve(RoutingContext context, OidcRequestContext<OidcTenantConfig> requestContext) {
        String resolvedTenantId = context.get(OidcUtils.TENANT_ID_ATTRIBUTE);
        if (resolvedTenantId != null) { 
1

            return null;
        }

        String path = context.request().path(); 
2

        if (path.endsWith("tenant-a")) {
            return Uni.createFrom().item(createTenantConfig("tenant-a", "client-a", "secret-a"));
        } else if (path.endsWith("tenant-b")) {
            return Uni.createFrom().item(createTenantConfig("tenant-b", "client-b", "secret-b"));
        }

        // Default tenant id
        return null;
    }

    private OidcTenantConfig createTenantConfig(String tenantId, String clientId, String secret) {
        final OidcTenantConfig config = OidcTenantConfig
                .authServerUrl("http://localhost:8180/realms/"  + tenantId)
                .tenantId(tenantId)
                .clientId(clientId)
                .credentials(secret)
                .applicationType(ApplicationType.WEB_APP)
                .build();
        return config;
    }
}
Copy to Clipboard Toggle word wrap
1
Let Quarkus use the already resolved tenant configuration if it has been resolved earlier.
2
Check the request path to create tenant configurations.

The default configuration may look like this:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/default
quarkus.oidc.client-id=client-default
quarkus.oidc.credentials.secret=secret-default
quarkus.oidc.application-type=web-app
Copy to Clipboard Toggle word wrap

The preceding example assumes that the tenant-a, tenant-b and default tenants are all used to protect the same endpoint paths. In other words, after the user has authenticated with the tenant-a configuration, this user will not be able to choose to authenticate with the tenant-b or default configuration before this user logs out and has a session cookie cleared or expired.

The situation where multiple OIDC web-app tenants protect the tenant-specific paths is less typical and also requires an extra care. When multiple OIDC web-app tenants such as tenant-a, tenant-b and default tenants are used to control access to the tenant specific paths, the users authenticated with one OIDC provider must not be able to access the paths requiring an authentication with another provider, otherwise the results can be unpredictable, most likely causing unexpected authentication failures. For example, if the tenant-a authentication requires a Keycloak authentication and the tenant-b authentication requires an Auth0 authentication, then, if the tenant-a authenticated user attempts to access a path secured by the tenant-b configuration, then the session cookie will not be verified, since the Auth0 public verification keys can not be used to verify the tokens signed by Keycloak. An easy, recommended way to avoid multiple web-app tenants conflicting with each other is to set the tenant specific session path as shown in the following example:

package io.quarkus.it.keycloak;

import jakarta.enterprise.context.ApplicationScoped;
import io.quarkus.oidc.OidcRequestContext;
import io.quarkus.oidc.OidcTenantConfig;
import io.quarkus.oidc.OidcTenantConfig.ApplicationType;
import io.quarkus.oidc.TenantConfigResolver;
import io.quarkus.oidc.runtime.OidcUtils;
import io.smallrye.mutiny.Uni;
import io.vertx.ext.web.RoutingContext;

@ApplicationScoped
public class CustomTenantConfigResolver implements TenantConfigResolver {

    @Override
    public Uni<OidcTenantConfig> resolve(RoutingContext context, OidcRequestContext<OidcTenantConfig> requestContext) {
        String resolvedTenantId = context.get(OidcUtils.TENANT_ID_ATTRIBUTE);
        if (resolvedTenantId != null) { 
1

            return null;
        }

        String path = context.request().path(); 
2

        if (path.endsWith("tenant-a")) {
            return Uni.createFrom().item(createTenantConfig("tenant-a", "/tenant-a", "client-a", "secret-a"));
        } else if (path.endsWith("tenant-b")) {
            return Uni.createFrom().item(createTenantConfig("tenant-b", "/tenant-b", "client-b", "secret-b"));
        }

        // Default tenant id
        return null;
    }

    private OidcTenantConfig createTenantConfig(String tenantId, String cookiePath, String clientId, String secret) {
        final OidcTenantConfig config = OidcTenantConfig
                .authServerUrl("http://localhost:8180/realms/" + tenantId)
                .tenantId(tenantId)
                .clientId(clientId)
                .credentials(secret)
                .applicationType(ApplicationType.WEB_APP)
                .authentication().cookiePath(cookiePath).end()  
3

                .build();
        return config;
    }
}
Copy to Clipboard Toggle word wrap
1
Let Quarkus use the already resolved tenant configuration if it has been resolved earlier.
2
Check the request path to create tenant configurations.
3
Set the tenant-specific cookie paths which makes sure the session cookie is only visible to the tenant which created it.

The default tenant configuration should be adjusted like this:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/default
quarkus.oidc.client-id=client-default
quarkus.oidc.credentials.secret=secret-default
quarkus.oidc.authentication.cookie-path=/default
quarkus.oidc.application-type=web-app
Copy to Clipboard Toggle word wrap

Having the same session cookie path when multiple OIDC web-app tenants protect the tenant-specific paths is not recommended and should be avoided as it requires even more care from the custom resolvers, for example:

package io.quarkus.it.keycloak;

import jakarta.enterprise.context.ApplicationScoped;
import io.quarkus.oidc.OidcRequestContext;
import io.quarkus.oidc.OidcTenantConfig;
import io.quarkus.oidc.OidcTenantConfig.ApplicationType;
import io.quarkus.oidc.TenantConfigResolver;
import io.quarkus.oidc.runtime.OidcUtils;
import io.smallrye.mutiny.Uni;
import io.vertx.ext.web.RoutingContext;

@ApplicationScoped
public class CustomTenantConfigResolver implements TenantConfigResolver {

    @Override
    public Uni<OidcTenantConfig> resolve(RoutingContext context, OidcRequestContext<OidcTenantConfig> requestContext) {

        String path = context.request().path(); 
1

        if (path.endsWith("tenant-a")) {
            String resolvedTenantId = context.get(OidcUtils.TENANT_ID_ATTRIBUTE);
	    if (resolvedTenantId != null) {
	        if ("tenant-a".equals(resolvedTenantId)) { 
2

	            return null;
	        } else {
	           // Require a "tenant-a" authentication
                   context.remove(OidcUtils.TENANT_ID_ATTRIBUTE); 
3

	        }
            }
            return Uni.createFrom().item(createTenantConfig("tenant-a", "client-a", "secret-a"));
        } else if (path.endsWith("tenant-b")) {
            String resolvedTenantId = context.get(OidcUtils.TENANT_ID_ATTRIBUTE);
	    if (resolvedTenantId != null) {
	        if ("tenant-b".equals(resolvedTenantId)) { 
4

	            return null;
	        } else {
	            // Require a "tenant-b" authentication
                   context.remove(OidcUtils.TENANT_ID_ATTRIBUTE); 
5

	        }
            }
            return Uni.createFrom().item(createTenantConfig("tenant-b", "client-b", "secret-b"));
        }

        // Set default tenant id
        context.put(OidcUtils.TENANT_ID_ATTRIBUTE, OidcUtils.DEFAULT_TENANT_ID); 
6

        return null;
    }

    private OidcTenantConfig createTenantConfig(String tenantId, String clientId, String secret) {
        final OidcTenantConfig config = OidcTenantConfig
            .authServerUrl("http://localhost:8180/realms/"  + tenantId)
            .tenantId(tenantId)
            .clientId(clientId)
            .credentials(secret)
            .applicationType(ApplicationType.WEB_APP)
            .build();
        return config;
    }
}
Copy to Clipboard Toggle word wrap
1
Check the request path to create tenant configurations.
2 4
Let Quarkus use the already resolved tenant configuration if the already resolved tenant is expected for the current path.
3 5
Remove the tenant-id attribute if the already resolved tenant configuration is not expected for the current path.
6
Use the default tenant for all other paths. It is equivalent to removing the tenant-id attribute.

5.11. Disabling tenant configurations

Custom TenantResolver and TenantConfigResolver implementations might return null if no tenant can be inferred from the current request and a fallback to the default tenant configuration is required.

If you expect the custom resolvers always to resolve a tenant, you do not need to configure the default tenant resolution.

  • To turn off the default tenant configuration, set quarkus.oidc.tenant-enabled=false.
Note

The default tenant configuration is automatically disabled when quarkus.oidc.auth-server-url is not configured, but either custom tenant configurations are available or TenantConfigResolver is registered.

Be aware that tenant-specific configurations can also be disabled, for example: quarkus.oidc.tenant-a.tenant-enabled=false.

Static OIDC tenants can be created programmatically like in the example below:

package io.quarkus.it.oidc;

import io.quarkus.oidc.Oidc;
import io.quarkus.oidc.OidcTenantConfig;
import jakarta.enterprise.event.Observes;

public class OidcStartup {

    void observe(@Observes Oidc oidc) { 
1

        oidc.create(OidcTenantConfig.authServerUrl("http://localhost:8180/realms/tenant-one").tenantId("tenant-one").build()); 
2

        oidc.create(OidcTenantConfig.authServerUrl("http://localhost:8180/realms/tenant-two").tenantId("tenant-two").build()); 
3

    }

}
Copy to Clipboard Toggle word wrap
1
Observe OIDC event.
2
Create OIDC tenant 'tenant-one'.
3
Create OIDC tenant 'tenant-two'.

The code above is a programmatic equivalent to the following configuration in the application.properties file:

quarkus.oidc.tenant-one.auth-server-url=http://localhost:8180/realms/tenant-one
quarkus.oidc.tenant-two.auth-server-url=http://localhost:8180/realms/tenant-two
Copy to Clipboard Toggle word wrap

5.13. References

As a Quarkus developer, you configure the Quarkus OpenID Connect (OIDC) extension by setting the following properties in the src/main/resources/application.properties file.

6.1. OIDC configuration

🔒 Fixed at build time - Configuration property fixed at build time - All other configuration properties are overridable at runtime

Expand

Configuration property

Type

Default

🔒 Fixed at build time quarkus.oidc.enabled

If the OIDC extension is enabled.

Environment variable: QUARKUS_OIDC_ENABLED

boolean

true

🔒 Fixed at build time quarkus.oidc.default-token-cache-enabled

Enable the registration of the Default TokenIntrospection and UserInfo Cache implementation bean. Note: This only enables the default implementation. It requires configuration to be activated. See OidcConfig#tokenCache.

Environment variable: QUARKUS_OIDC_DEFAULT_TOKEN_CACHE_ENABLED

boolean

true

quarkus.oidc.resolve-tenants-with-issuer

If OIDC tenants should be resolved using the bearer access token’s issuer (iss) claim value.

Environment variable: QUARKUS_OIDC_RESOLVE_TENANTS_WITH_ISSUER

boolean

false

quarkus.oidc.auth-server-url

quarkus.oidc."tenant".auth-server-url

The base URL of the OpenID Connect (OIDC) server, for example, https://host:port/auth. Do not set this property if you use 'quarkus-oidc' and the public key verification (public-key) or certificate chain verification only (certificate-chain) is required. The OIDC discovery endpoint is called by default by appending a .well-known/openid-configuration path to this URL. For Keycloak, use https://host:port/realms/{realm}, replacing {realm} with the Keycloak realm name.

Environment variable: QUARKUS_OIDC_AUTH_SERVER_URL

string

 

quarkus.oidc.discovery-enabled

quarkus.oidc."tenant".discovery-enabled

Discovery of the OIDC endpoints. If not enabled, you must configure the OIDC endpoint URLs individually.

Environment variable: QUARKUS_OIDC_DISCOVERY_ENABLED

boolean

true

quarkus.oidc.registration-path

quarkus.oidc."tenant".registration-path

The relative path or absolute URL of the OIDC dynamic client registration endpoint. Set if discovery-enabled is false or a discovered token endpoint path must be customized.

Environment variable: QUARKUS_OIDC_REGISTRATION_PATH

string

 

quarkus.oidc.connection-delay

quarkus.oidc."tenant".connection-delay

The duration to attempt the initial connection to an OIDC server. For example, setting the duration to 20S allows 10 retries, each 2 seconds apart. This property is only effective when the initial OIDC connection is created. For dropped connections, use the connection-retry-count property instead.

Environment variable: QUARKUS_OIDC_CONNECTION_DELAY

Duration ℹ️ Duration format

 

quarkus.oidc.connection-retry-count

quarkus.oidc."tenant".connection-retry-count

The number of times to retry re-establishing an existing OIDC connection if it is temporarily lost. Different from connection-delay, which applies only to initial connection attempts. For instance, if a request to the OIDC token endpoint fails due to a connection issue, it will be retried as per this setting.

Environment variable: QUARKUS_OIDC_CONNECTION_RETRY_COUNT

int

3

quarkus.oidc.connection-timeout

quarkus.oidc."tenant".connection-timeout

The number of seconds after which the current OIDC connection request times out.

Environment variable: QUARKUS_OIDC_CONNECTION_TIMEOUT

Duration ℹ️ Duration format

10S

quarkus.oidc.use-blocking-dns-lookup

quarkus.oidc."tenant".use-blocking-dns-lookup

Whether DNS lookup should be performed on the worker thread. Use this option when you can see logged warnings about blocked Vert.x event loop by HTTP requests to OIDC server.

Environment variable: QUARKUS_OIDC_USE_BLOCKING_DNS_LOOKUP

boolean

false

quarkus.oidc.max-pool-size

quarkus.oidc."tenant".max-pool-size

The maximum size of the connection pool used by the WebClient.

Environment variable: QUARKUS_OIDC_MAX_POOL_SIZE

int

 

quarkus.oidc.follow-redirects

quarkus.oidc."tenant".follow-redirects

Follow redirects automatically when WebClient gets HTTP 302. When this property is disabled only a single redirect to exactly the same original URI is allowed but only if one or more cookies were set during the redirect request.

Environment variable: QUARKUS_OIDC_FOLLOW_REDIRECTS

boolean

true

quarkus.oidc.token-path

quarkus.oidc."tenant".token-path

The OIDC token endpoint that issues access and refresh tokens; specified as a relative path or absolute URL. Set if discovery-enabled is false or a discovered token endpoint path must be customized.

Environment variable: QUARKUS_OIDC_TOKEN_PATH

string

 

quarkus.oidc.revoke-path

quarkus.oidc."tenant".revoke-path

The relative path or absolute URL of the OIDC token revocation endpoint.

Environment variable: QUARKUS_OIDC_REVOKE_PATH

string

 

quarkus.oidc.client-id

quarkus.oidc."tenant".client-id

The client id of the application. Each application has a client id that is used to identify the application. Setting the client id is not required if application-type is service and no token introspection is required.

Environment variable: QUARKUS_OIDC_CLIENT_ID

string

 

quarkus.oidc.client-name

quarkus.oidc."tenant".client-name

The client name of the application. It is meant to represent a human readable description of the application which you may provide when an application (client) is registered in an OpenId Connect provider’s dashboard. For example, you can set this property to have more informative log messages which record an activity of the given client.

Environment variable: QUARKUS_OIDC_CLIENT_NAME

string

 

quarkus.oidc.tenant-id

quarkus.oidc."tenant".tenant-id

A unique tenant identifier. It can be set by TenantConfigResolver providers, which resolve the tenant configuration dynamically.

Environment variable: QUARKUS_OIDC_TENANT_ID

string

 

quarkus.oidc.tenant-enabled

quarkus.oidc."tenant".tenant-enabled

If this tenant configuration is enabled. The default tenant is disabled if it is not configured but a TenantConfigResolver that resolves tenant configurations is registered, or named tenants are configured. In this case, you do not need to disable the default tenant.

Environment variable: QUARKUS_OIDC_TENANT_ENABLED

boolean

true

quarkus.oidc.application-type

quarkus.oidc."tenant".application-type

The application type, which can be one of the following ApplicationType values.

Environment variable: QUARKUS_OIDC_APPLICATION_TYPE

web-app: A WEB_APP is a client that serves pages, usually a front-end application. For this type of client the Authorization Code Flow is defined as the preferred method for authenticating users.

service: A SERVICE is a client that has a set of protected HTTP resources, usually a backend application following the RESTful Architectural Design. For this type of client, the Bearer Authorization method is defined as the preferred method for authenticating and authorizing users.

hybrid: A combined SERVICE and WEB_APP client. For this type of client, the Bearer Authorization method is used if the Authorization header is set and Authorization Code Flow - if not.

service

quarkus.oidc.authorization-path

quarkus.oidc."tenant".authorization-path

The relative path or absolute URL of the OpenID Connect (OIDC) authorization endpoint, which authenticates users. You must set this property for web-app applications if OIDC discovery is disabled. This property is ignored if OIDC discovery is enabled.

Environment variable: QUARKUS_OIDC_AUTHORIZATION_PATH

string

 

quarkus.oidc.user-info-path

quarkus.oidc."tenant".user-info-path

The relative path or absolute URL of the OIDC UserInfo endpoint. You must set this property for web-app applications if OIDC discovery is disabled and the authentication.user-info-required property is enabled. This property is ignored if OIDC discovery is enabled.

Environment variable: QUARKUS_OIDC_USER_INFO_PATH

string

 

quarkus.oidc.introspection-path

quarkus.oidc."tenant".introspection-path

Relative path or absolute URL of the OIDC RFC7662 introspection endpoint which can introspect both opaque and JSON Web Token (JWT) tokens. This property must be set if OIDC discovery is disabled and 1) the opaque bearer access tokens must be verified or 2) JWT tokens must be verified while the cached JWK verification set with no matching JWK is being refreshed. This property is ignored if the discovery is enabled.

Environment variable: QUARKUS_OIDC_INTROSPECTION_PATH

string

 

quarkus.oidc.jwks-path

quarkus.oidc."tenant".jwks-path

Relative path or absolute URL of the OIDC JSON Web Key Set (JWKS) endpoint which returns a JSON Web Key Verification Set. This property should be set if OIDC discovery is disabled and the local JWT verification is required. This property is ignored if the discovery is enabled.

Environment variable: QUARKUS_OIDC_JWKS_PATH

string

 

quarkus.oidc.end-session-path

quarkus.oidc."tenant".end-session-path

Relative path or absolute URL of the OIDC end_session_endpoint. This property must be set if OIDC discovery is disabled and RP Initiated Logout support for the web-app applications is required. This property is ignored if the discovery is enabled.

Environment variable: QUARKUS_OIDC_END_SESSION_PATH

string

 

quarkus.oidc.tenant-paths

quarkus.oidc."tenant".tenant-paths

The paths which must be secured by this tenant. Tenant with the most specific path wins. Please see the Configure tenant paths section of the OIDC multitenancy guide for explanation of allowed path patterns.

Environment variable: QUARKUS_OIDC_TENANT_PATHS

list of string

 

quarkus.oidc.public-key

quarkus.oidc."tenant".public-key

The public key for the local JWT token verification. OIDC server connection is not created when this property is set.

Environment variable: QUARKUS_OIDC_PUBLIC_KEY

string

 

quarkus.oidc.allow-token-introspection-cache

quarkus.oidc."tenant".allow-token-introspection-cache

Allow caching the token introspection data. Note enabling this property does not enable the cache itself but only permits to cache the token introspection for a given tenant. If the default token cache can be used, see OidcConfig.TokenCache to enable it.

Environment variable: QUARKUS_OIDC_ALLOW_TOKEN_INTROSPECTION_CACHE

boolean

true

quarkus.oidc.allow-user-info-cache

quarkus.oidc."tenant".allow-user-info-cache

Allow caching the user info data. Note enabling this property does not enable the cache itself but only permits to cache the user info data for a given tenant. If the default token cache can be used, see OidcConfig.TokenCache to enable it.

Environment variable: QUARKUS_OIDC_ALLOW_USER_INFO_CACHE

boolean

true

quarkus.oidc.cache-user-info-in-idtoken

quarkus.oidc."tenant".cache-user-info-in-idtoken

Allow inlining UserInfo in IdToken instead of caching it in the token cache. This property is only checked when an internal IdToken is generated when OAuth2 providers do not return IdToken. Inlining UserInfo in the generated IdToken allows to store it in the session cookie and avoids introducing a cached state.

Inlining UserInfo in the generated IdToken is enabled if the session cookie is encrypted and the UserInfo cache is not enabled or caching UserInfo is disabled for the current tenant with the allow-user-info-cache property set to false.

Environment variable: QUARKUS_OIDC_CACHE_USER_INFO_IN_IDTOKEN

boolean

 

quarkus.oidc.provider

quarkus.oidc."tenant".provider

Well known OpenId Connect provider identifier

Environment variable: QUARKUS_OIDC_PROVIDER

apple, discord, facebook, github, google, linkedin, mastodon, microsoft, slack, spotify, strava, twitch, twitter, x

 

OIDC Dev UI configuration which is effective in dev mode only

Type

Default

🔒 Fixed at build time quarkus.oidc.devui.grant.type

Grant type which will be used to acquire a token to test the OIDC 'service' applications

Environment variable: QUARKUS_OIDC_DEVUI_GRANT_TYPE

client: 'client_credentials' grant

password: 'password' grant

code: 'authorization_code' grant

implicit: 'implicit' grant

 

🔒 Fixed at build time quarkus.oidc.devui.grant-options."option-name"

Grant options

Environment variable: QUARKUS_OIDC_DEVUI_GRANT_OPTIONS__OPTION_NAME_

Map<String,Map<String,String>>

 

🔒 Fixed at build time quarkus.oidc.devui.web-client-timeout

The WebClient timeout. Use this property to configure how long an HTTP client used by Dev UI handlers will wait for a response when requesting tokens from OpenId Connect Provider and sending them to the service endpoint.

Environment variable: QUARKUS_OIDC_DEVUI_WEB_CLIENT_TIMEOUT

Duration ℹ️ Duration format

4S

HTTP proxy configuration

Type

Default

quarkus.oidc.proxy.host

quarkus.oidc."tenant".proxy.host

The host name or IP address of the Proxy.
Note: If the OIDC adapter requires a Proxy to talk with the OIDC server (Provider), set this value to enable the usage of a Proxy.

Environment variable: QUARKUS_OIDC_PROXY_HOST

string

 

quarkus.oidc.proxy.port

quarkus.oidc."tenant".proxy.port

The port number of the Proxy. The default value is 80.

Environment variable: QUARKUS_OIDC_PROXY_PORT

int

80

quarkus.oidc.proxy.username

quarkus.oidc."tenant".proxy.username

The username, if the Proxy needs authentication.

Environment variable: QUARKUS_OIDC_PROXY_USERNAME

string

 

quarkus.oidc.proxy.password

quarkus.oidc."tenant".proxy.password

The password, if the Proxy needs authentication.

Environment variable: QUARKUS_OIDC_PROXY_PASSWORD

string

 

TLS configuration

Type

Default

quarkus.oidc.tls.tls-configuration-name

quarkus.oidc."tenant".tls.tls-configuration-name

The name of the TLS configuration to use.

If a name is configured, it uses the configuration from quarkus.tls.<name>.* If a name is configured, but no TLS configuration is found with that name then an error will be thrown.

The default TLS configuration is not used by default.

Environment variable: QUARKUS_OIDC_TLS_TLS_CONFIGURATION_NAME

string

 

Different authentication options for OIDC client to access OIDC token and other secured endpoints

Type

Default

quarkus.oidc.credentials.secret

quarkus.oidc."tenant".credentials.secret

The client secret used by the client_secret_basic authentication method. Must be set unless a secret is set in client-secret or jwt client authentication is required. You can use client-secret.value instead, but both properties are mutually exclusive.

Environment variable: QUARKUS_OIDC_CREDENTIALS_SECRET

string

 

quarkus.oidc.credentials.client-secret.value

quarkus.oidc."tenant".credentials.client-secret.value

The client secret value. This value is ignored if credentials.secret is set. Must be set unless a secret is set in client-secret or jwt client authentication is required.

Environment variable: QUARKUS_OIDC_CREDENTIALS_CLIENT_SECRET_VALUE

string

 

quarkus.oidc.credentials.client-secret.provider.name

quarkus.oidc."tenant".credentials.client-secret.provider.name

The CredentialsProvider bean name, which should only be set if more than one CredentialsProvider is registered

Environment variable: QUARKUS_OIDC_CREDENTIALS_CLIENT_SECRET_PROVIDER_NAME

string

 

quarkus.oidc.credentials.client-secret.provider.keyring-name

quarkus.oidc."tenant".credentials.client-secret.provider.keyring-name

The CredentialsProvider keyring name. The keyring name is only required when the CredentialsProvider being used requires the keyring name to look up the secret, which is often the case when a CredentialsProvider is shared by multiple extensions to retrieve credentials from a more dynamic source like a vault instance or secret manager

Environment variable: QUARKUS_OIDC_CREDENTIALS_CLIENT_SECRET_PROVIDER_KEYRING_NAME

string

 

quarkus.oidc.credentials.client-secret.provider.key

quarkus.oidc."tenant".credentials.client-secret.provider.key

The CredentialsProvider client secret key

Environment variable: QUARKUS_OIDC_CREDENTIALS_CLIENT_SECRET_PROVIDER_KEY

string

 

quarkus.oidc.credentials.client-secret.method

quarkus.oidc."tenant".credentials.client-secret.method

The authentication method. If the clientSecret.value secret is set, this method is basic by default.

Environment variable: QUARKUS_OIDC_CREDENTIALS_CLIENT_SECRET_METHOD

basic: client_secret_basic (default): The client id and secret are submitted with the HTTP Authorization Basic scheme.

post: client_secret_post: The client id and secret are submitted as the client_id and client_secret form parameters.

post-jwt: client_secret_jwt: The client id and generated JWT secret are submitted as the client_id and client_secret form parameters.

query: client id and secret are submitted as HTTP query parameters. This option is only supported by the OIDC extension.

 

quarkus.oidc.credentials.jwt.source

quarkus.oidc."tenant".credentials.jwt.source

JWT token source: OIDC provider client or an existing JWT bearer token.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_SOURCE

client: JWT token is generated by the OIDC provider client to support client_secret_jwt and private_key_jwt authentication methods.

bearer: JWT bearer token is used as a client assertion: https://www.rfc-editor.org/rfc/rfc7523#section-2.2.

client

quarkus.oidc.credentials.jwt.token-path

quarkus.oidc."tenant".credentials.jwt.token-path

Path to a file with a JWT bearer token that should be used as a client assertion. This path can only be set when JWT source (source()) is set to Source#BEARER.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_TOKEN_PATH

path

 

quarkus.oidc.credentials.jwt.secret

quarkus.oidc."tenant".credentials.jwt.secret

If provided, indicates that JWT is signed using a secret key. It is mutually exclusive with key, key-file and key-store properties.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_SECRET

string

 

quarkus.oidc.credentials.jwt.secret-provider.name

quarkus.oidc."tenant".credentials.jwt.secret-provider.name

The CredentialsProvider bean name, which should only be set if more than one CredentialsProvider is registered

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_SECRET_PROVIDER_NAME

string

 

quarkus.oidc.credentials.jwt.secret-provider.keyring-name

quarkus.oidc."tenant".credentials.jwt.secret-provider.keyring-name

The CredentialsProvider keyring name. The keyring name is only required when the CredentialsProvider being used requires the keyring name to look up the secret, which is often the case when a CredentialsProvider is shared by multiple extensions to retrieve credentials from a more dynamic source like a vault instance or secret manager

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_SECRET_PROVIDER_KEYRING_NAME

string

 

quarkus.oidc.credentials.jwt.secret-provider.key

quarkus.oidc."tenant".credentials.jwt.secret-provider.key

The CredentialsProvider client secret key

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_SECRET_PROVIDER_KEY

string

 

quarkus.oidc.credentials.jwt.key

quarkus.oidc."tenant".credentials.jwt.key

String representation of a private key. If provided, indicates that JWT is signed using a private key in PEM or JWK format. It is mutually exclusive with secret, key-file and key-store properties. You can use the signature-algorithm property to override the default key algorithm, RS256.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_KEY

string

 

quarkus.oidc.credentials.jwt.key-file

quarkus.oidc."tenant".credentials.jwt.key-file

If provided, indicates that JWT is signed using a private key in PEM or JWK format. It is mutually exclusive with secret, key and key-store properties. You can use the signature-algorithm property to override the default key algorithm, RS256.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_KEY_FILE

string

 

quarkus.oidc.credentials.jwt.key-store-file

quarkus.oidc."tenant".credentials.jwt.key-store-file

If provided, indicates that JWT is signed using a private key from a keystore. It is mutually exclusive with secret, key and key-file properties.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_KEY_STORE_FILE

string

 

quarkus.oidc.credentials.jwt.key-store-password

quarkus.oidc."tenant".credentials.jwt.key-store-password

A parameter to specify the password of the keystore file.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_KEY_STORE_PASSWORD

string

 

quarkus.oidc.credentials.jwt.key-id

quarkus.oidc."tenant".credentials.jwt.key-id

The private key id or alias.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_KEY_ID

string

 

quarkus.oidc.credentials.jwt.key-password

quarkus.oidc."tenant".credentials.jwt.key-password

The private key password.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_KEY_PASSWORD

string

 

quarkus.oidc.credentials.jwt.audience

quarkus.oidc."tenant".credentials.jwt.audience

The JWT audience (aud) claim value. By default, the audience is set to the address of the OpenId Connect Provider’s token endpoint.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_AUDIENCE

string

 

quarkus.oidc.credentials.jwt.token-key-id

quarkus.oidc."tenant".credentials.jwt.token-key-id

The key identifier of the signing key added as a JWT kid header.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_TOKEN_KEY_ID

string

 

quarkus.oidc.credentials.jwt.issuer

quarkus.oidc."tenant".credentials.jwt.issuer

The issuer of the signing key added as a JWT iss claim. The default value is the client id.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_ISSUER

string

 

quarkus.oidc.credentials.jwt.subject

quarkus.oidc."tenant".credentials.jwt.subject

Subject of the signing key added as a JWT sub claim The default value is the client id.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_SUBJECT

string

 

quarkus.oidc.credentials.jwt.claims."claim-name"

quarkus.oidc."tenant".credentials.jwt.claims."claim-name"

Additional claims.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_CLAIMS__CLAIM_NAME_

Map<String,String>

 

quarkus.oidc.credentials.jwt.signature-algorithm

quarkus.oidc."tenant".credentials.jwt.signature-algorithm

The signature algorithm used for the key-file property. Supported values: RS256 (default), RS384, RS512, PS256, PS384, PS512, ES256, ES384, ES512, HS256, HS384, HS512.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_SIGNATURE_ALGORITHM

string

 

quarkus.oidc.credentials.jwt.lifespan

quarkus.oidc."tenant".credentials.jwt.lifespan

The JWT lifespan in seconds. This value is added to the time at which the JWT was issued to calculate the expiration time.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_LIFESPAN

int

10

quarkus.oidc.credentials.jwt.assertion

quarkus.oidc."tenant".credentials.jwt.assertion

If true then the client authentication token is a JWT bearer grant assertion. Instead of producing 'client_assertion' and 'client_assertion_type' form properties, only 'assertion' is produced. This option is only supported by the OIDC client extension.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_ASSERTION

boolean

false

Optional introspection endpoint-specific basic authentication configuration

Type

Default

quarkus.oidc.introspection-credentials.name

quarkus.oidc."tenant".introspection-credentials.name

Name

Environment variable: QUARKUS_OIDC_INTROSPECTION_CREDENTIALS_NAME

string

 

quarkus.oidc.introspection-credentials.secret

quarkus.oidc."tenant".introspection-credentials.secret

Secret

Environment variable: QUARKUS_OIDC_INTROSPECTION_CREDENTIALS_SECRET

string

 

quarkus.oidc.introspection-credentials.include-client-id

quarkus.oidc."tenant".introspection-credentials.include-client-id

Include OpenId Connect Client ID configured with quarkus.oidc.client-id.

Environment variable: QUARKUS_OIDC_INTROSPECTION_CREDENTIALS_INCLUDE_CLIENT_ID

boolean

true

Configuration to find and parse custom claims which contain roles

Type

Default

quarkus.oidc.roles.role-claim-path

quarkus.oidc."tenant".roles.role-claim-path

A list of paths to claims containing an array of groups. Each path starts from the top level JWT JSON object and can contain multiple segments. Each segment represents a JSON object name only; for example: "realm/groups". Use double quotes with the namespace-qualified claim names. This property can be used if a token has no groups claim but has the groups set in one or more different claims.

Environment variable: QUARKUS_OIDC_ROLES_ROLE_CLAIM_PATH

list of string

 

quarkus.oidc.roles.role-claim-separator

quarkus.oidc."tenant".roles.role-claim-separator

The separator for splitting strings that contain multiple group values. It is only used if the "role-claim-path" property points to one or more custom claims whose values are strings. A single space is used by default because the standard scope claim can contain a space-separated sequence.

Environment variable: QUARKUS_OIDC_ROLES_ROLE_CLAIM_SEPARATOR

string

 

quarkus.oidc.roles.source

quarkus.oidc."tenant".roles.source

Source of the principal roles.

Environment variable: QUARKUS_OIDC_ROLES_SOURCE

idtoken: ID Token - the default value for the web-app applications.

accesstoken: Access Token - the default value for the service applications; can also be used as the source of roles for the web-app applications.

userinfo: User Info

 

Configuration to customize validation of token claims

Type

Default

quarkus.oidc.token.issuer

quarkus.oidc."tenant".token.issuer

The expected issuer iss claim value. This property overrides the issuer property, which might be set in OpenId Connect provider’s well-known configuration. If the iss claim value varies depending on the host, IP address, or tenant id of the provider, you can skip the issuer verification by setting this property to any, but it should be done only when other options (such as configuring the provider to use the fixed iss claim value) are not possible.

Environment variable: QUARKUS_OIDC_TOKEN_ISSUER

string

 

quarkus.oidc.token.audience

quarkus.oidc."tenant".token.audience

The expected audience aud claim value, which can be a string or an array of strings. Note the audience claim is verified for ID tokens by default. ID token audience must be equal to the value of quarkus.oidc.client-id property. Use this property to override the expected value if your OpenID Connect provider sets a different audience claim value in ID tokens. Set it to any if your provider does not set ID token audience` claim. Audience verification for access tokens is only done if this property is configured.

Environment variable: QUARKUS_OIDC_TOKEN_AUDIENCE

list of string

 

quarkus.oidc.token.subject-required

quarkus.oidc."tenant".token.subject-required

Require that the token includes a sub (subject) claim which is a unique and never reassigned identifier for the current user. Note that if you enable this property and if UserInfo is also required, both the token and UserInfo sub claims must be present and match each other.

Environment variable: QUARKUS_OIDC_TOKEN_SUBJECT_REQUIRED

boolean

false

quarkus.oidc.token.required-claims."claim-name"

quarkus.oidc."tenant".token.required-claims."claim-name"

A map of required claims and their expected values. For example, quarkus.oidc.token.required-claims.org_id = org_xyz would require tokens to have the org_id claim to be present and set to org_xyz. Strings are the only supported types. Use SecurityIdentityAugmentor to verify claims of other types or complex claims.

Environment variable: QUARKUS_OIDC_TOKEN_REQUIRED_CLAIMS__CLAIM_NAME_

Map<String,String>

 

quarkus.oidc.token.token-type

quarkus.oidc."tenant".token.token-type

Expected token type

Environment variable: QUARKUS_OIDC_TOKEN_TOKEN_TYPE

string

 

quarkus.oidc.token.lifespan-grace

quarkus.oidc."tenant".token.lifespan-grace

Life span grace period in seconds. When checking token expiry, current time is allowed to be later than token expiration time by at most the configured number of seconds. When checking token issuance, current time is allowed to be sooner than token issue time by at most the configured number of seconds.

Environment variable: QUARKUS_OIDC_TOKEN_LIFESPAN_GRACE

int

 

quarkus.oidc.token.age

quarkus.oidc."tenant".token.age

Token age. It allows for the number of seconds to be specified that must not elapse since the iat (issued at) time. A small leeway to account for clock skew which can be configured with quarkus.oidc.token.lifespan-grace to verify the token expiry time can also be used to verify the token age property. Note that setting this property does not relax the requirement that Bearer and Code Flow JWT tokens must have a valid (exp) expiry claim value. The only exception where setting this property relaxes the requirement is when a logout token is sent with a back-channel logout request since the current OpenId Connect Back-Channel specification does not explicitly require the logout tokens to contain an exp claim. However, even if the current logout token is allowed to have no exp claim, the exp claim is still verified if the logout token contains it.

Environment variable: QUARKUS_OIDC_TOKEN_AGE

Duration ℹ️ Duration format

 

quarkus.oidc.token.issued-at-required

quarkus.oidc."tenant".token.issued-at-required

Require that the token includes a iat (issued at) claim Set this property to false if your JWT token does not contain an iat (issued at) claim. Note that ID token is always required to have an iat claim and therefore this property has no impact on the ID token verification process.

Environment variable: QUARKUS_OIDC_TOKEN_ISSUED_AT_REQUIRED

boolean

true

quarkus.oidc.token.principal-claim

quarkus.oidc."tenant".token.principal-claim

Name of the claim which contains a principal name. By default, the upn, preferred_username and sub claims are checked.

Environment variable: QUARKUS_OIDC_TOKEN_PRINCIPAL_CLAIM

string

 

quarkus.oidc.token.refresh-expired

quarkus.oidc."tenant".token.refresh-expired

Refresh expired authorization code flow ID or access tokens. If this property is enabled, a refresh token request is performed if the authorization code ID or access token has expired and, if successful, the local session is updated with the new set of tokens. Otherwise, the local session is invalidated and the user redirected to the OpenID Provider to re-authenticate. In this case, the user might not be challenged again if the OIDC provider session is still active. For this option be effective the authentication.session-age-extension property should also be set to a nonzero value since the refresh token is currently kept in the user session. This option is valid only when the application is of type ApplicationType#WEB_APP. This property is enabled if quarkus.oidc.token.refresh-token-time-skew is configured, you do not need to enable this property manually in this case.

Environment variable: QUARKUS_OIDC_TOKEN_REFRESH_EXPIRED

boolean

false

quarkus.oidc.token.refresh-token-time-skew

quarkus.oidc."tenant".token.refresh-token-time-skew

The refresh token time skew, in seconds. If this property is enabled, the configured number of seconds is added to the current time when checking if the authorization code ID or access token should be refreshed. If the sum is greater than the authorization code ID or access token’s expiration time, a refresh is going to happen.

Environment variable: QUARKUS_OIDC_TOKEN_REFRESH_TOKEN_TIME_SKEW

Duration ℹ️ Duration format

 

quarkus.oidc.token.forced-jwk-refresh-interval

quarkus.oidc."tenant".token.forced-jwk-refresh-interval

The forced JWK set refresh interval in minutes.

Environment variable: QUARKUS_OIDC_TOKEN_FORCED_JWK_REFRESH_INTERVAL

Duration ℹ️ Duration format

10M

quarkus.oidc.token.header

quarkus.oidc."tenant".token.header

Custom HTTP header that contains a bearer token. This option is valid only when the application is of type ApplicationType#SERVICE.

Environment variable: QUARKUS_OIDC_TOKEN_HEADER

string

 

quarkus.oidc.token.authorization-scheme

quarkus.oidc."tenant".token.authorization-scheme

HTTP Authorization header scheme.

Environment variable: QUARKUS_OIDC_TOKEN_AUTHORIZATION_SCHEME

string

Bearer

quarkus.oidc.token.signature-algorithm

quarkus.oidc."tenant".token.signature-algorithm

Required signature algorithm. OIDC providers support many signature algorithms but if necessary you can restrict Quarkus application to accept tokens signed only using an algorithm configured with this property.

Environment variable: QUARKUS_OIDC_TOKEN_SIGNATURE_ALGORITHM

rs256, rs384, rs512, ps256, ps384, ps512, es256, es384, es512, eddsa

 

quarkus.oidc.token.decryption-key-location

quarkus.oidc."tenant".token.decryption-key-location

Decryption key location. JWT tokens can be inner-signed and encrypted by OpenId Connect providers. However, it is not always possible to remotely introspect such tokens because the providers might not control the private decryption keys. In such cases set this property to point to the file containing the decryption private key in PEM or JSON Web Key (JWK) format. If this property is not set and the private_key_jwt client authentication method is used, the private key used to sign the client authentication JWT tokens are also used to decrypt the encrypted ID tokens.

Environment variable: QUARKUS_OIDC_TOKEN_DECRYPTION_KEY_LOCATION

string

 

quarkus.oidc.token.allow-jwt-introspection

quarkus.oidc."tenant".token.allow-jwt-introspection

Allow the remote introspection of JWT tokens when no matching JWK key is available. This property is set to true by default for backward-compatibility reasons. It is planned that this default value will be changed to false in an upcoming release. Also note this property is ignored if JWK endpoint URI is not available and introspecting the tokens is the only verification option.

Environment variable: QUARKUS_OIDC_TOKEN_ALLOW_JWT_INTROSPECTION

boolean

true

quarkus.oidc.token.require-jwt-introspection-only

quarkus.oidc."tenant".token.require-jwt-introspection-only

Require that JWT tokens are only introspected remotely.

Environment variable: QUARKUS_OIDC_TOKEN_REQUIRE_JWT_INTROSPECTION_ONLY

boolean

false

quarkus.oidc.token.allow-opaque-token-introspection

quarkus.oidc."tenant".token.allow-opaque-token-introspection

Allow the remote introspection of the opaque tokens. Set this property to false if only JWT tokens are expected.

Environment variable: QUARKUS_OIDC_TOKEN_ALLOW_OPAQUE_TOKEN_INTROSPECTION

boolean

true

quarkus.oidc.token.customizer-name

quarkus.oidc."tenant".token.customizer-name

Token customizer name. Allows to select a tenant specific token customizer as a named bean. Prefer using TenantFeature qualifier when registering custom TokenCustomizer. Use this property only to refer to TokenCustomizer implementations provided by this extension.

Environment variable: QUARKUS_OIDC_TOKEN_CUSTOMIZER_NAME

string

 

quarkus.oidc.token.verify-access-token-with-user-info

quarkus.oidc."tenant".token.verify-access-token-with-user-info

Indirectly verify that the opaque (binary) access token is valid by using it to request UserInfo. Opaque access token is considered valid if the provider accepted this token and returned a valid UserInfo. You should only enable this option if the opaque access tokens must be accepted but OpenId Connect provider does not have a token introspection endpoint. This property has no effect when JWT tokens must be verified.

Environment variable: QUARKUS_OIDC_TOKEN_VERIFY_ACCESS_TOKEN_WITH_USER_INFO

boolean

false

quarkus.oidc.token.binding.certificate

quarkus.oidc."tenant".token.binding.certificate

If a bearer access token must be bound to the client mTLS certificate. It requires that JWT tokens must contain a confirmation cnf claim with a SHA256 certificate thumbprint matching the client mTLS certificate’s SHA256 certificate thumbprint.

For opaque tokens, SHA256 certificate thumbprint must be returned in their introspection response.

Environment variable: QUARKUS_OIDC_TOKEN_BINDING_CERTIFICATE

boolean

false

RP-initiated, back-channel and front-channel logout configuration

Type

Default

quarkus.oidc.logout.path

quarkus.oidc."tenant".logout.path

The relative path of the logout endpoint at the application. If provided, the application is able to initiate the logout through this endpoint in conformance with the OpenID Connect RP-Initiated Logout specification.

Environment variable: QUARKUS_OIDC_LOGOUT_PATH

string

 

quarkus.oidc.logout.post-logout-path

quarkus.oidc."tenant".logout.post-logout-path

Relative path of the application endpoint where the user should be redirected to after logging out from the OpenID Connect Provider. This endpoint URI must be properly registered at the OpenID Connect Provider as a valid redirect URI.

Environment variable: QUARKUS_OIDC_LOGOUT_POST_LOGOUT_PATH

string

 

quarkus.oidc.logout.post-logout-uri-param

quarkus.oidc."tenant".logout.post-logout-uri-param

Name of the post logout URI parameter which is added as a query parameter to the logout redirect URI.

Environment variable: QUARKUS_OIDC_LOGOUT_POST_LOGOUT_URI_PARAM

string

post_logout_redirect_uri

quarkus.oidc.logout.extra-params."query-parameter-name"

quarkus.oidc."tenant".logout.extra-params."query-parameter-name"

Additional properties which is added as the query parameters to the logout redirect URI.

Environment variable: QUARKUS_OIDC_LOGOUT_EXTRA_PARAMS__QUERY_PARAMETER_NAME_

Map<String,String>

 

quarkus.oidc.logout.backchannel.path

quarkus.oidc."tenant".logout.backchannel.path

The relative path of the Back-Channel Logout endpoint at the application. It must start with the forward slash '/', for example, '/back-channel-logout'. This value is always resolved relative to 'quarkus.http.root-path'.

Environment variable: QUARKUS_OIDC_LOGOUT_BACKCHANNEL_PATH

string

 

quarkus.oidc.logout.backchannel.token-cache-size

quarkus.oidc."tenant".logout.backchannel.token-cache-size

Maximum number of logout tokens that can be cached before they are matched against ID tokens stored in session cookies.

Environment variable: QUARKUS_OIDC_LOGOUT_BACKCHANNEL_TOKEN_CACHE_SIZE

int

10

quarkus.oidc.logout.backchannel.token-cache-time-to-live

quarkus.oidc."tenant".logout.backchannel.token-cache-time-to-live

Number of minutes a logout token can be cached for.

Environment variable: QUARKUS_OIDC_LOGOUT_BACKCHANNEL_TOKEN_CACHE_TIME_TO_LIVE

Duration ℹ️ Duration format

10M

quarkus.oidc.logout.backchannel.clean-up-timer-interval

quarkus.oidc."tenant".logout.backchannel.clean-up-timer-interval

Token cache timer interval. If this property is set, a timer checks and removes the stale entries periodically.

Environment variable: QUARKUS_OIDC_LOGOUT_BACKCHANNEL_CLEAN_UP_TIMER_INTERVAL

Duration ℹ️ Duration format

 

quarkus.oidc.logout.backchannel.logout-token-key

quarkus.oidc."tenant".logout.backchannel.logout-token-key

Logout token claim whose value is used as a key for caching the tokens. Only sub (subject) and sid (session id) claims can be used as keys. Set it to sid only if ID tokens issued by the OIDC provider have no sub but have sid claim.

Environment variable: QUARKUS_OIDC_LOGOUT_BACKCHANNEL_LOGOUT_TOKEN_KEY

string

sub

quarkus.oidc.logout.frontchannel.path

quarkus.oidc."tenant".logout.frontchannel.path

The relative path of the Front-Channel Logout endpoint at the application.

Environment variable: QUARKUS_OIDC_LOGOUT_FRONTCHANNEL_PATH

string

 

Configuration of the certificate chain which can be used to verify tokens

Type

Default

quarkus.oidc.certificate-chain.leaf-certificate-name

quarkus.oidc."tenant".certificate-chain.leaf-certificate-name

Common name of the leaf certificate. It must be set if the trust-store-file does not have this certificate imported.

Environment variable: QUARKUS_OIDC_CERTIFICATE_CHAIN_LEAF_CERTIFICATE_NAME

string

 

quarkus.oidc.certificate-chain.trust-store-file

quarkus.oidc."tenant".certificate-chain.trust-store-file

Truststore file which keeps thumbprints of the trusted certificates.

Environment variable: QUARKUS_OIDC_CERTIFICATE_CHAIN_TRUST_STORE_FILE

path

 

quarkus.oidc.certificate-chain.trust-store-password

quarkus.oidc."tenant".certificate-chain.trust-store-password

A parameter to specify the password of the truststore file if it is configured with trust-store-file.

Environment variable: QUARKUS_OIDC_CERTIFICATE_CHAIN_TRUST_STORE_PASSWORD

string

 

quarkus.oidc.certificate-chain.trust-store-cert-alias

quarkus.oidc."tenant".certificate-chain.trust-store-cert-alias

A parameter to specify the alias of the truststore certificate.

Environment variable: QUARKUS_OIDC_CERTIFICATE_CHAIN_TRUST_STORE_CERT_ALIAS

string

 

quarkus.oidc.certificate-chain.trust-store-file-type

quarkus.oidc."tenant".certificate-chain.trust-store-file-type

An optional parameter to specify type of the truststore file. If not given, the type is automatically detected based on the file name.

Environment variable: QUARKUS_OIDC_CERTIFICATE_CHAIN_TRUST_STORE_FILE_TYPE

string

 

Configuration for managing an authorization code flow

Type

Default

quarkus.oidc.authentication.response-mode

quarkus.oidc."tenant".authentication.response-mode

Authorization code flow response mode.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_RESPONSE_MODE

query: Authorization response parameters are encoded in the query string added to the redirect_uri

form-post: Authorization response parameters are encoded as HTML form values that are auto-submitted in the browser and transmitted by the HTTP POST method using the application/x-www-form-urlencoded content type

query

quarkus.oidc.authentication.redirect-path

quarkus.oidc."tenant".authentication.redirect-path

The relative path for calculating a redirect_uri query parameter. It has to start from a forward slash and is appended to the request URI’s host and port. For example, if the current request URI is https://localhost:8080/service, a redirect_uri parameter is set to https://localhost:8080/ if this property is set to / and be the same as the request URI if this property has not been configured. Note the original request URI is restored after the user has authenticated if restorePathAfterRedirect is set to true.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_REDIRECT_PATH

string

 

quarkus.oidc.authentication.restore-path-after-redirect

quarkus.oidc."tenant".authentication.restore-path-after-redirect

If this property is set to true, the original request URI which was used before the authentication is restored after the user has been redirected back to the application. Note if redirectPath property is not set, the original request URI is restored even if this property is disabled.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_RESTORE_PATH_AFTER_REDIRECT

boolean

false

quarkus.oidc.authentication.remove-redirect-parameters

quarkus.oidc."tenant".authentication.remove-redirect-parameters

Remove the query parameters such as code and state set by the OIDC server on the redirect URI after the user has authenticated by redirecting a user to the same URI but without the query parameters.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_REMOVE_REDIRECT_PARAMETERS

boolean

true

quarkus.oidc.authentication.error-path

quarkus.oidc."tenant".authentication.error-path

Relative path to the public endpoint which processes the error response from the OIDC authorization endpoint. If the user authentication has failed, the OIDC provider returns an error and an optional error_description parameters, instead of the expected authorization code. If this property is set, the user is redirected to the endpoint which can return a user-friendly error description page. It has to start from a forward slash and is appended to the request URI’s host and port. For example, if it is set as /error and the current request URI is https://localhost:8080/callback?error=invalid_scope, a redirect is made to https://localhost:8080/error?error=invalid_scope. If this property is not set, HTTP 401 status is returned in case of the user authentication failure.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_ERROR_PATH

string

 

quarkus.oidc.authentication.session-expired-path

quarkus.oidc."tenant".authentication.session-expired-path

Relative path to the public endpoint which an authenticated user is redirected to when the session has expired.

When the OIDC session has expired and the session can not be refreshed, a user is redirected to the OIDC provider to re-authenticate. The user experience may not be ideal in this case as it may not be obvious to the authenticated user why an authentication challenge is returned.

Set this property if you would like the user whose session has expired be redirected to a public application specific page instead, which can inform that the session has expired and advise the user to re-authenticated by following a link to the secured initial entry page.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_SESSION_EXPIRED_PATH

string

 

quarkus.oidc.authentication.verify-access-token

quarkus.oidc."tenant".authentication.verify-access-token

Both ID and access tokens are fetched from the OIDC provider as part of the authorization code flow.

ID token is always verified on every user request as the primary token which is used to represent the principal and extract the roles.

Authorization code flow access token is meant to be propagated to downstream services and is not verified by default unless quarkus.oidc.roles.source property is set to accesstoken which means the authorization decision is based on the roles extracted from the access token.

Authorization code flow access token verification is also enabled if this token is injected as JsonWebToken. Set this property to false if it is not required.

Bearer access token is always verified.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_VERIFY_ACCESS_TOKEN

boolean

true when access token is injected as the JsonWebToken bean, false otherwise

quarkus.oidc.authentication.force-redirect-https-scheme

quarkus.oidc."tenant".authentication.force-redirect-https-scheme

Force https as the redirect_uri parameter scheme when running behind an SSL/TLS terminating reverse proxy. This property, if enabled, also affects the logout post_logout_redirect_uri and the local redirect requests.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_FORCE_REDIRECT_HTTPS_SCHEME

boolean

false

quarkus.oidc.authentication.scopes

quarkus.oidc."tenant".authentication.scopes

List of scopes

Environment variable: QUARKUS_OIDC_AUTHENTICATION_SCOPES

list of string

 

quarkus.oidc.authentication.scope-separator

quarkus.oidc."tenant".authentication.scope-separator

The separator which is used when more than one scope is configured. A single space is used by default.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_SCOPE_SEPARATOR

string

 

quarkus.oidc.authentication.nonce-required

quarkus.oidc."tenant".authentication.nonce-required

Require that ID token includes a nonce claim which must match nonce authentication request query parameter. Enabling this property can help mitigate replay attacks. Do not enable this property if your OpenId Connect provider does not support setting nonce in ID token or if you work with OAuth2 provider such as GitHub which does not issue ID tokens.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_NONCE_REQUIRED

boolean

false

quarkus.oidc.authentication.add-openid-scope

quarkus.oidc."tenant".authentication.add-openid-scope

Add the openid scope automatically to the list of scopes. This is required for OpenId Connect providers, but does not work for OAuth2 providers such as Twitter OAuth2, which do not accept this scope and throw errors.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_ADD_OPENID_SCOPE

boolean

true

quarkus.oidc.authentication.extra-params."parameter-name"

quarkus.oidc."tenant".authentication.extra-params."parameter-name"

Additional properties added as query parameters to the authentication redirect URI.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_EXTRA_PARAMS__PARAMETER_NAME_

Map<String,String>

 

quarkus.oidc.authentication.forward-params

quarkus.oidc."tenant".authentication.forward-params

Request URL query parameters which, if present, are added to the authentication redirect URI.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_FORWARD_PARAMS

list of string

 

quarkus.oidc.authentication.cookie-force-secure

quarkus.oidc."tenant".authentication.cookie-force-secure

If enabled the state, session, and post logout cookies have their secure parameter set to true when HTTP is used. It might be necessary when running behind an SSL/TLS terminating reverse proxy. The cookies are always secure if HTTPS is used, even if this property is set to false.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_COOKIE_FORCE_SECURE

boolean

false

quarkus.oidc.authentication.cookie-suffix

quarkus.oidc."tenant".authentication.cookie-suffix

Cookie name suffix. For example, a session cookie name for the default OIDC tenant is q_session but can be changed to q_session_test if this property is set to test.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_COOKIE_SUFFIX

string

 

quarkus.oidc.authentication.cookie-path

quarkus.oidc."tenant".authentication.cookie-path

Cookie path parameter value which, if set, is used to set a path parameter for the session, state and post logout cookies. The cookie-path-header property, if set, is checked first.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_COOKIE_PATH

string

/

quarkus.oidc.authentication.cookie-path-header

quarkus.oidc."tenant".authentication.cookie-path-header

Cookie path header parameter value which, if set, identifies the incoming HTTP header whose value is used to set a path parameter for the session, state and post logout cookies. If the header is missing, the cookie-path property is checked.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_COOKIE_PATH_HEADER

string

 

quarkus.oidc.authentication.cookie-domain

quarkus.oidc."tenant".authentication.cookie-domain

Cookie domain parameter value which, if set, is used for the session, state and post logout cookies.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_COOKIE_DOMAIN

string

 

quarkus.oidc.authentication.cookie-same-site

quarkus.oidc."tenant".authentication.cookie-same-site

SameSite attribute for the session cookie.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_COOKIE_SAME_SITE

strict, lax, none

lax

quarkus.oidc.authentication.allow-multiple-code-flows

quarkus.oidc."tenant".authentication.allow-multiple-code-flows

If a state cookie is present, a state query parameter must also be present and both the state cookie name suffix and state cookie value must match the value of the state query parameter when the redirect path matches the current path. However, if multiple authentications are attempted from the same browser, for example, from the different browser tabs, then the currently available state cookie might represent the authentication flow initiated from another tab and not related to the current request. Disable this property to permit only a single authorization code flow in the same browser.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_ALLOW_MULTIPLE_CODE_FLOWS

boolean

true

quarkus.oidc.authentication.fail-on-missing-state-param

quarkus.oidc."tenant".authentication.fail-on-missing-state-param

Fail with the HTTP 401 error if the state cookie is present but no state query parameter is present.

When either multiple authentications are disabled or the redirect URL matches the original request URL, the stale state cookie might remain in the browser cache from the earlier failed redirect to an OpenId Connect provider and be visible during the current request. For example, if Single-page application (SPA) uses XHR to handle redirects to the provider which does not support CORS for its authorization endpoint, the browser blocks it and the state cookie created by Quarkus remains in the browser cache. Quarkus reports an authentication failure when it detects such an old state cookie but find no matching state query parameter.

Reporting HTTP 401 error is usually the right thing to do in such cases, it minimizes a risk of the browser redirect loop but also can identify problems in the way SPA or Quarkus application manage redirects. For example, enabling java-script-auto-redirect or having the provider redirect to URL configured with redirect-path might be needed to avoid such errors.

However, setting this property to false might help if the above options are not suitable. It causes a new authentication redirect to OpenId Connect provider. Doing so might increase the risk of browser redirect loops.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_FAIL_ON_MISSING_STATE_PARAM

boolean

false

quarkus.oidc.authentication.fail-on-unresolved-kid

quarkus.oidc."tenant".authentication.fail-on-unresolved-kid

Fail with the HTTP 401 error if the ID token signature can not be verified during the re-authentication only due to an unresolved token key identifier (kid).

This property might need to be disabled when multiple tab authentications are allowed, with one of the tabs keeping an expired ID token with its kid unresolved due to the verification key set refreshed due to another tab initiating an authorization code flow. In such cases, instead of failing with the HTTP 401 error, redirecting the user to re-authenticate with the HTTP 302 status may provide better user experience.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_FAIL_ON_UNRESOLVED_KID

boolean

true

quarkus.oidc.authentication.user-info-required

quarkus.oidc."tenant".authentication.user-info-required

If this property is set to true, an OIDC UserInfo endpoint is called.

This property is enabled automatically if quarkus.oidc.roles.source is set to userinfo or quarkus.oidc.token.verify-access-token-with-user-info is set to true or quarkus.oidc.authentication.id-token-required is set to false, the current OIDC tenant must support a UserInfo endpoint in these cases.

It is also enabled automatically if io.quarkus.oidc.UserInfo injection point is detected but only if the current OIDC tenant supports a UserInfo endpoint.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_USER_INFO_REQUIRED

boolean

true when UserInfo bean is injected, false otherwise

quarkus.oidc.authentication.session-age-extension

quarkus.oidc."tenant".authentication.session-age-extension

Session age extension in minutes. The user session age property is set to the value of the ID token life-span by default and the user is redirected to the OIDC provider to re-authenticate once the session has expired. If this property is set to a nonzero value, then the expired ID token can be refreshed before the session has expired. This property is ignored if the token.refresh-expired property has not been enabled.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_SESSION_AGE_EXTENSION

Duration ℹ️ Duration format

5M

quarkus.oidc.authentication.state-cookie-age

quarkus.oidc."tenant".authentication.state-cookie-age

State cookie age in minutes. State cookie is created every time a new authorization code flow redirect starts and removed when this flow is completed. State cookie name is unique by default, see allow-multiple-code-flows. Keep its age to the reasonable minimum value such as 5 minutes or less.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_STATE_COOKIE_AGE

Duration ℹ️ Duration format

5M

quarkus.oidc.authentication.java-script-auto-redirect

quarkus.oidc."tenant".authentication.java-script-auto-redirect

If this property is set to true, a normal 302 redirect response is returned if the request was initiated by a JavaScript API such as XMLHttpRequest or Fetch and the current user needs to be (re)authenticated, which might not be desirable for Single-page applications (SPA) since it automatically following the redirect might not work given that OIDC authorization endpoints typically do not support CORS.

If this property is set to false, a status code of 499 is returned to allow SPA to handle the redirect manually if a request header identifying current request as a JavaScript request is found. X-Requested-With request header with its value set to either JavaScript or XMLHttpRequest is expected by default if this property is enabled. You can register a custom JavaScriptRequestChecker to do a custom JavaScript request check instead.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_JAVA_SCRIPT_AUTO_REDIRECT

boolean

true

quarkus.oidc.authentication.id-token-required

quarkus.oidc."tenant".authentication.id-token-required

Requires that ID token is available when the authorization code flow completes. Disable this property only when you need to use the authorization code flow with OAuth2 providers which do not return ID token - an internal IdToken is generated in such cases.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_ID_TOKEN_REQUIRED

boolean

true

quarkus.oidc.authentication.internal-id-token-lifespan

quarkus.oidc."tenant".authentication.internal-id-token-lifespan

Internal ID token lifespan. This property is only checked when an internal IdToken is generated when OAuth2 providers do not return IdToken. If this property is not configured then an access token expires_in property in the OAuth2 authorization code flow response is used to set an internal IdToken lifespan.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_INTERNAL_ID_TOKEN_LIFESPAN

Duration ℹ️ Duration format

 

quarkus.oidc.authentication.pkce-required

quarkus.oidc."tenant".authentication.pkce-required

Requires that a Proof Key for Code Exchange (PKCE) is used.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_PKCE_REQUIRED

boolean

false

quarkus.oidc.authentication.state-secret

quarkus.oidc."tenant".authentication.state-secret

Secret used to encrypt Proof Key for Code Exchange (PKCE) code verifier and/or nonce in the code flow state. This secret should be at least 32 characters long.

If this secret is not set, the client secret configured with either quarkus.oidc.credentials.secret or quarkus.oidc.credentials.client-secret.value is checked. Finally, quarkus.oidc.credentials.jwt.secret which can be used for client_jwt_secret authentication is checked. A client secret is not be used as a state encryption secret if it is less than 32 characters long.

The secret is auto-generated if it remains uninitialized after checking all of these properties.

Error is reported if the secret length is less than 16 characters.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_STATE_SECRET

string

 

Configuration to complete an authorization code flow grant

Type

Default

quarkus.oidc.code-grant.extra-params."parameter-name"

quarkus.oidc."tenant".code-grant.extra-params."parameter-name"

Additional parameters, in addition to the required code and redirect-uri parameters, which must be included to complete the authorization code grant request.

Environment variable: QUARKUS_OIDC_CODE_GRANT_EXTRA_PARAMS__PARAMETER_NAME_

Map<String,String>

 

quarkus.oidc.code-grant.headers."header-name"

quarkus.oidc."tenant".code-grant.headers."header-name"

Custom HTTP headers which must be sent to complete the authorization code grant request.

Environment variable: QUARKUS_OIDC_CODE_GRANT_HEADERS__HEADER_NAME_

Map<String,String>

 

Default token state manager configuration

Type

Default

quarkus.oidc.token-state-manager.strategy

quarkus.oidc."tenant".token-state-manager.strategy

Default TokenStateManager strategy.

Environment variable: QUARKUS_OIDC_TOKEN_STATE_MANAGER_STRATEGY

keep-all-tokens: Keep ID, access and refresh tokens.

id-token: Keep ID token only

id-refresh-tokens: Keep ID and refresh tokens only

keep-all-tokens

quarkus.oidc.token-state-manager.split-tokens

quarkus.oidc."tenant".token-state-manager.split-tokens

Default TokenStateManager keeps all tokens (ID, access and refresh) returned in the authorization code grant response in a single session cookie by default. Enable this property to minimize a session cookie size

Environment variable: QUARKUS_OIDC_TOKEN_STATE_MANAGER_SPLIT_TOKENS

boolean

false

quarkus.oidc.token-state-manager.encryption-required

quarkus.oidc."tenant".token-state-manager.encryption-required

Mandates that the Default TokenStateManager encrypt the session cookie that stores the tokens.

Environment variable: QUARKUS_OIDC_TOKEN_STATE_MANAGER_ENCRYPTION_REQUIRED

boolean

true

quarkus.oidc.token-state-manager.encryption-secret

quarkus.oidc."tenant".token-state-manager.encryption-secret

The secret used by the Default TokenStateManager to encrypt the session cookie storing the tokens when encryption-required property is enabled.

If this secret is not set, the client secret configured with either quarkus.oidc.credentials.secret or quarkus.oidc.credentials.client-secret.value is checked. Finally, quarkus.oidc.credentials.jwt.secret which can be used for client_jwt_secret authentication is checked. The secret is auto-generated every time an application starts if it remains uninitialized after checking all of these properties. Generated secret can not decrypt the session cookie encrypted before the restart, therefore a user re-authentication will be required.

The length of the secret used to encrypt the tokens should be at least 32 characters long. A warning is logged if the secret length is less than 16 characters.

Environment variable: QUARKUS_OIDC_TOKEN_STATE_MANAGER_ENCRYPTION_SECRET

string

 

quarkus.oidc.token-state-manager.encryption-algorithm

quarkus.oidc."tenant".token-state-manager.encryption-algorithm

Session cookie key encryption algorithm

Environment variable: QUARKUS_OIDC_TOKEN_STATE_MANAGER_ENCRYPTION_ALGORITHM

a256-gcmkw: Content encryption key will be generated and encrypted using the A256GCMKW algorithm and the configured encryption secret. The generated content encryption key will be used to encrypt the session cookie content.

dir: The configured key encryption secret will be used as the content encryption key to encrypt the session cookie content. Using the direct encryption avoids a content encryption key generation step and will make the encrypted session cookie sequence slightly shorter. Avoid using the direct encryption if the encryption secret is less than 32 characters long.

a256-gcmkw

How JsonWebKey verification key set should be acquired and managed

Type

Default

quarkus.oidc.jwks.resolve-early

quarkus.oidc."tenant".jwks.resolve-early

If JWK verification keys should be fetched at the moment a connection to the OIDC provider is initialized.

Disabling this property delays the key acquisition until the moment the current token has to be verified. Typically it can only be necessary if the token or other telated request properties provide an additional context which is required to resolve the keys correctly.

Environment variable: QUARKUS_OIDC_JWKS_RESOLVE_EARLY

boolean

true

quarkus.oidc.jwks.cache-size

quarkus.oidc."tenant".jwks.cache-size

Maximum number of JWK keys that can be cached. This property is ignored if the resolve-early property is set to true.

Environment variable: QUARKUS_OIDC_JWKS_CACHE_SIZE

int

10

quarkus.oidc.jwks.cache-time-to-live

quarkus.oidc."tenant".jwks.cache-time-to-live

Number of minutes a JWK key can be cached for. This property is ignored if the resolve-early property is set to true.

Environment variable: QUARKUS_OIDC_JWKS_CACHE_TIME_TO_LIVE

Duration ℹ️ Duration format

10M

quarkus.oidc.jwks.clean-up-timer-interval

quarkus.oidc."tenant".jwks.clean-up-timer-interval

Cache timer interval. If this property is set, a timer checks and removes the stale entries periodically. This property is ignored if the resolve-early property is set to true.

Environment variable: QUARKUS_OIDC_JWKS_CLEAN_UP_TIMER_INTERVAL

Duration ℹ️ Duration format

 

quarkus.oidc.jwks.try-all

quarkus.oidc."tenant".jwks.try-all

In case there is no key identifier ('kid') or certificate thumbprints ('x5t', 'x5t#S256') specified in the JOSE header and no key could be determined, check all available keys matching the token algorithm ('alg') header value.

Environment variable: QUARKUS_OIDC_JWKS_TRY_ALL

boolean

false

Default TokenIntrospection and UserInfo Cache configuration

Type

Default

quarkus.oidc.token-cache.max-size

Maximum number of cache entries. Set it to a positive value if the cache has to be enabled.

Environment variable: QUARKUS_OIDC_TOKEN_CACHE_MAX_SIZE

int

0

quarkus.oidc.token-cache.time-to-live

Maximum amount of time a given cache entry is valid for.

Environment variable: QUARKUS_OIDC_TOKEN_CACHE_TIME_TO_LIVE

Duration ℹ️ Duration format

3M

quarkus.oidc.token-cache.clean-up-timer-interval

Clean up timer interval. If this property is set then a timer will check and remove the stale entries periodically.

Environment variable: QUARKUS_OIDC_TOKEN_CACHE_CLEAN_UP_TIMER_INTERVAL

Duration ℹ️ Duration format

 
About the Duration format

To write duration values, use the standard java.time.Duration format. See the Duration#parse() Java API documentation for more information.

You can also use a simplified format, starting with a number:

  • If the value is only a number, it represents time in seconds.
  • If the value is a number followed by ms, it represents time in milliseconds.

In other cases, the simplified format is translated to the java.time.Duration format for parsing:

  • If the value is a number followed by h, m, or s, it is prefixed with PT.
  • If the value is a number followed by d, it is prefixed with P.

6.2. Keycloak Dev Services configuration

🔒 Fixed at build time - Configuration property fixed at build time - All other configuration properties are overridable at runtime

Expand

Configuration property

Type

Default

🔒 Fixed at build time quarkus.keycloak.devservices.enabled

Flag to enable (default) or disable Dev Services. When enabled, Dev Services for Keycloak automatically configures and starts Keycloak in Dev or Test mode, and when Docker is running.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_ENABLED

boolean

true

🔒 Fixed at build time quarkus.keycloak.devservices.image-name

The container image name for Dev Services providers. Defaults to a Quarkus-based Keycloak image. For a WildFly-based distribution, use an image like quay.io/keycloak/keycloak:19.0.3-legacy. Keycloak Quarkus and WildFly images are initialized differently. Dev Services for Keycloak will assume it is a Keycloak Quarkus image unless the image version ends with -legacy. Override with quarkus.keycloak.devservices.keycloak-x-image.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_IMAGE_NAME

string

quay.io/keycloak/keycloak:26.1.3

🔒 Fixed at build time quarkus.keycloak.devservices.keycloak-x-image

Indicates if a Keycloak-X image is used. By default, the image is identified by keycloak-x in the image name. For custom images, override with quarkus.keycloak.devservices.keycloak-x-image. You do not need to set this property if the default check works.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_KEYCLOAK_X_IMAGE

boolean

 

🔒 Fixed at build time quarkus.keycloak.devservices.shared

Determines if the Keycloak container is shared. When shared, Quarkus uses label-based service discovery to find and reuse a running Keycloak container, so a second one is not started. Otherwise, if a matching container is not is found, a new container is started. The service discovery uses the quarkus-dev-service-label label, whose value is set by the service-name property. Container sharing is available only in dev mode.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_SHARED

boolean

true

🔒 Fixed at build time quarkus.keycloak.devservices.service-name

The value of the quarkus-dev-service-keycloak label for identifying the Keycloak container. Used in shared mode to locate an existing container with this label. If not found, a new container is initialized with this label. Applicable only in dev mode.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_SERVICE_NAME

string

quarkus

🔒 Fixed at build time quarkus.keycloak.devservices.realm-path

A comma-separated list of class or file system paths to Keycloak realm files. This list is used to initialize Keycloak. The first value in this list is used to initialize default tenant connection properties.

To learn more about Keycloak realm files, consult the Importing and Exporting Keycloak Realms documentation.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_REALM_PATH

list of string

 

🔒 Fixed at build time quarkus.keycloak.devservices.resource-aliases."alias-name"

Aliases to additional class or file system resources that are used to initialize Keycloak. Each map entry represents a mapping between an alias and a class or file system resource path.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_RESOURCE_ALIASES__ALIAS_NAME_

Map<String,String>

 

🔒 Fixed at build time quarkus.keycloak.devservices.resource-mappings."resource-name"

Additional class or file system resources that are used to initialize Keycloak. Each map entry represents a mapping between a class or file system resource path alias and the Keycloak container location.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_RESOURCE_MAPPINGS__RESOURCE_NAME_

Map<String,String>

 

🔒 Fixed at build time quarkus.keycloak.devservices.java-opts

The JAVA_OPTS passed to the keycloak JVM

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_JAVA_OPTS

string

 

🔒 Fixed at build time quarkus.keycloak.devservices.show-logs

Show Keycloak log messages with a "Keycloak:" prefix.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_SHOW_LOGS

boolean

false

🔒 Fixed at build time quarkus.keycloak.devservices.start-command

Keycloak start command. Use this property to experiment with Keycloak start options, see https://www.keycloak.org/server/all-config. Note, it is ignored when loading legacy Keycloak WildFly images.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_START_COMMAND

string

 

🔒 Fixed at build time quarkus.keycloak.devservices.features

Keycloak features. Use this property to enable one or more experimental Keycloak features. Note, if you also have to customize a Keycloak start-command(), you can use a --features option as part of the start command sequence, instead of configuring this property.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_FEATURES

list of string

 

🔒 Fixed at build time quarkus.keycloak.devservices.realm-name

The name of the Keycloak realm. This property is used to create the realm if the realm file pointed to by the realm-path property does not exist. The default value is quarkus in this case. It is recommended to always set this property so that Dev Services for Keycloak can identify the realm name without parsing the realm file.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_REALM_NAME

string

 

🔒 Fixed at build time quarkus.keycloak.devservices.create-realm

Specifies whether to create the Keycloak realm when no realm file is found at the realm-path. Set to false if the realm is to be created using either the Keycloak Administration Console or the Keycloak Admin API provided by io.quarkus.test.common.QuarkusTestResourceLifecycleManager.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_CREATE_REALM

boolean

true

🔒 Fixed at build time quarkus.keycloak.devservices.create-client

Specifies whether to create the default client id quarkus-app with a secret secret and register them if the create-realm property is set to true. For OIDC extension configuration properties quarkus.oidc.client.id and quarkus.oidc.credentials.secret will be configured. For OIDC Client extension configuration properties quarkus.oidc-client.client.id and quarkus.oidc-client.credentials.secret will be configured. Set to false if clients have to be created using either the Keycloak Administration Console or the Keycloak Admin API provided by io.quarkus.test.common.QuarkusTestResourceLifecycleManager or registered dynamically.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_CREATE_CLIENT

boolean

true

🔒 Fixed at build time quarkus.keycloak.devservices.start-with-disabled-tenant

Specifies whether to start the container even if the default OIDC tenant is disabled. Setting this property to true may be necessary in a multi-tenant OIDC setup, especially when OIDC tenants are created dynamically.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_START_WITH_DISABLED_TENANT

boolean

false

🔒 Fixed at build time quarkus.keycloak.devservices.users."users"

A map of Keycloak usernames to passwords. If empty, default users alice and bob are created with their names as passwords. This map is used for user creation when no realm file is found at the realm-path.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_USERS__USERS_

Map<String,String>

 

🔒 Fixed at build time quarkus.keycloak.devservices.roles."role-name"

A map of roles for Keycloak users. If empty, default roles are assigned: alice receives admin and user roles, while other users receive user role. This map is used for role creation when no realm file is found at the realm-path.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_ROLES__ROLE_NAME_

Map<String,List<String>>

 

🔒 Fixed at build time quarkus.keycloak.devservices.port

The specific port for the dev service to listen on.

If not specified, a random port is selected.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_PORT

int

 

🔒 Fixed at build time quarkus.keycloak.devservices.container-env."environment-variable-name"

Environment variables to be passed to the container.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_CONTAINER_ENV__ENVIRONMENT_VARIABLE_NAME_

Map<String,String>

 

🔒 Fixed at build time quarkus.keycloak.devservices.container-memory-limit

Memory limit for Keycloak container

If not specified, 1250MiB is the default memory limit.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_CONTAINER_MEMORY_LIMIT

MemorySize ℹ️ MemorySize format

1250M

🔒 Fixed at build time quarkus.keycloak.devservices.web-client-timeout

The WebClient timeout. Use this property to configure how long an HTTP client used by OIDC dev service admin client will wait for a response from OpenId Connect Provider when acquiring admin token and creating realm.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_WEB_CLIENT_TIMEOUT

Duration ℹ️ Duration format

4S

About the Duration format

To write duration values, use the standard java.time.Duration format. See the Duration#parse() Java API documentation for more information.

You can also use a simplified format, starting with a number:

  • If the value is only a number, it represents time in seconds.
  • If the value is a number followed by ms, it represents time in milliseconds.

In other cases, the simplified format is translated to the java.time.Duration format for parsing:

  • If the value is a number followed by h, m, or s, it is prefixed with PT.
  • If the value is a number followed by d, it is prefixed with P.
About the MemorySize format

A size configuration option recognizes strings in this format (shown as a regular expression): [0-9]+[KkMmGgTtPpEeZzYy]?.

If no suffix is given, assume bytes.

6.3. References

Legal Notice

Copyright © 2025 Red Hat, Inc.
The text of and illustrations in this document are licensed by Red Hat under a Creative Commons Attribution–Share Alike 3.0 Unported license ("CC-BY-SA"). An explanation of CC-BY-SA is available at http://creativecommons.org/licenses/by-sa/3.0/. In accordance with CC-BY-SA, if you distribute this document or an adaptation of it, you must provide the URL for the original version.
Red Hat, as the licensor of this document, waives the right to enforce, and agrees not to assert, Section 4d of CC-BY-SA to the fullest extent permitted by applicable law.
Red Hat, Red Hat Enterprise Linux, the Shadowman logo, the Red Hat logo, JBoss, OpenShift, Fedora, the Infinity logo, and RHCE are trademarks of Red Hat, Inc., registered in the United States and other countries.
Linux® is the registered trademark of Linus Torvalds in the United States and other countries.
Java® is a registered trademark of Oracle and/or its affiliates.
XFS® is a trademark of Silicon Graphics International Corp. or its subsidiaries in the United States and/or other countries.
MySQL® is a registered trademark of MySQL AB in the United States, the European Union and other countries.
Node.js® is an official trademark of Joyent. Red Hat is not formally related to or endorsed by the official Joyent Node.js open source or commercial project.
The OpenStack® Word Mark and OpenStack logo are either registered trademarks/service marks or trademarks/service marks of the OpenStack Foundation, in the United States and other countries and are used with the OpenStack Foundation's permission. We are not affiliated with, endorsed or sponsored by the OpenStack Foundation, or the OpenStack community.
All other trademarks are the property of their respective owners.
Back to top
Red Hat logoGithubredditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust. Explore our recent updates.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

Theme

© 2025 Red Hat