Configure Java Clients for OAuth/OIDC on Confluent Cloud

Configure Java Kafka and Schema Registry clients for OAuth/OIDC on Confluent Cloud.

Prerequisites

Before you begin, ensure you have the following prerequisites:

  • Apache Kafka client: 4.1.0 or later. The examples on this page use the client credential properties that were added in 4.1.0. If you use Kafka client 4.0.x, see Configuration for Kafka client 4.0.x.

  • OAuth authentication is configured

  • Client configuration details

    • Client ID: Identifier for requesting OAuth tokens

    • Client secret: Secret for requesting OAuth tokens

    • Token endpoint URL: Location of access tokens

    • Scopes: The permissions your application requires as defined in your identity provider. For example, kafka:read kafka:write for Kafka, schema-registry for Schema Registry.

    • Cluster ID: Your cluster ID based on cluster type

    • Identity pool ID (pool-xxxxx): Optional

Add the following dependencies to your project:

  • org.apache.kafka:kafka-clients: The Kafka Java client, which includes the OAuthBearerLoginCallbackHandler used for OAuth.

  • com.fasterxml.jackson.core:jackson-databind: Required at runtime to parse the OAuth access token. The kafka-clients artifact doesn’t include this library as a transitive dependency, so you must add it explicitly.

  • org.bitbucket.b_c:jose4j: Required at runtime by the OAuthBearerLoginCallbackHandler to retrieve and validate OAuth tokens. The kafka-clients artifact doesn’t include this library as a transitive dependency, so you must add it explicitly.

  • io.confluent:kafka-schema-registry-client: Required only if you use Schema Registry. This artifact is available from the Confluent Maven repository (https://packages.confluent.io/maven/). Its version must match your kafka-clients version. For details, see Configure Schema Registry Java clients.

Maven dependencies example:

<repositories>
    <!-- Required only for kafka-schema-registry-client -->
    <repository>
        <id>confluent</id>
        <url>https://packages.confluent.io/maven/</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka-clients</artifactId>
        <version>4.4.0</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.21.7</version>
    </dependency>
    <dependency>
        <groupId>org.bitbucket.b_c</groupId>
        <artifactId>jose4j</artifactId>
        <version>0.9.6</version>
    </dependency>
    <!-- Required only if you use Schema Registry. Use the version from the
         Confluent Platform release that includes your kafka-clients version
         (Confluent Platform 8.4 includes Kafka 4.4). -->
    <dependency>
        <groupId>io.confluent</groupId>
        <artifactId>kafka-schema-registry-client</artifactId>
        <version>8.4.0</version>
    </dependency>
</dependencies>

Note

Dependency Management Best Practice: For production applications, consider using Maven properties or the Confluent Platform BOM (Bill of Materials) to manage dependency versions consistently. This ensures all Confluent Cloud components use compatible versions.

Maven properties example:

<properties>
    <java.version>11</java.version>
    <confluent.version>8.4.0</confluent.version>
</properties>

Configure Kafka Java clients

The Kafka client initiates authentication by requesting a token from the configured OAuth provider using client credentials. Once obtained, this token is sent to the Kafka broker with each connection request. The broker validates the token’s authenticity, expiration, and permissions before granting access.

The implementation class is:

org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginCallbackHandler

and accepts instances of the following:

org.apache.kafka.common.security.oauthbearer.OAuthBearerTokenCallback
org.apache.kafka.common.security.auth.SaslExtensionsCallback

The fully-qualified class name is provided to the client’s configuration of sasl.login.callback.handler.class.

Because the HTTP call made to the OAuth 2.0 provider might time out or transiently fail, a retry mechanism waits between attempts. The number of attempts made (including the first attempt) are variable as it uses an exponential backoff approach:

  1. Immediately, an attempt to connect to the HTTP endpoint is initiated.

  2. If the first attempt fails, a second attempt is initiated after the configurable number of milliseconds set in sasl.login.retry.backoff.ms.

  3. If the second attempt fails, the duration is doubled before a third attempt.

This pattern repeats as required until the maximum duration of sasl.login.retry.backoff.max.ms.

Configuration approach

Java clients use the JAAS (Java Authentication and Authorization Service) framework for SASL authentication. With Kafka client 4.1.0 and later, set the token endpoint URL, client credentials, and scope with the following client properties:

  • sasl.oauthbearer.token.endpoint.url

  • sasl.oauthbearer.client.credentials.client.id

  • sasl.oauthbearer.client.credentials.client.secret

  • sasl.oauthbearer.scope

Set the Confluent Cloud extensions (extension_logicalCluster and extension_identityPoolId) as options of the OAuthBearerLoginModule in the sasl.jaas.config property, as shown in the example below.

The clientId, clientSecret, and scope JAAS options that earlier versions used are deprecated starting with Kafka client 4.1.0 and will be removed in a future version. If you set both a property and the corresponding JAAS option, the property takes precedence.

Important

Starting with Kafka client 4.0.0, the client accesses only the OAuth URLs that you explicitly allow in the org.apache.kafka.sasl.oauthbearer.allowed.urls JVM system property. Add your token endpoint URL to this property, or the client fails at startup with a ConfigException. For example:

java -Dorg.apache.kafka.sasl.oauthbearer.allowed.urls=https://your-idp.com/oauth2/token -jar your-app.jar

Starting with Kafka client 4.1.0, any file that the client reads for OAuth, such as the sasl.oauthbearer.assertion.private.key.file or sasl.oauthbearer.assertion.template.file, must also be listed, by absolute path, in the org.apache.kafka.sasl.oauthbearer.allowed.files system property. Separate multiple values with commas.

JAAS configuration

  • Confluent Cloud cluster and identity pool IDs

Top-level configuration

  • SASL mechanism and protocol

  • Callback handler class

  • Token endpoint URL

  • OAuth client credentials (client ID, secret) and scope

  • Timeout and retry settings

Configuration example

For client secrets, add these OAuth-specific settings to your existing Kafka configuration:

Properties props = new Properties();

// Basic Kafka configuration
props.put("bootstrap.servers", "your-bootstrap-server:9092");
props.put("security.protocol", "SASL_SSL");
props.put("sasl.mechanism", "OAUTHBEARER");
props.put("sasl.login.callback.handler.class",
    "org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginCallbackHandler");

// OAuth configuration
props.put("sasl.oauthbearer.token.endpoint.url", "https://your-idp.com/oauth2/token");
props.put("sasl.oauthbearer.client.credentials.client.id", "your-client-id");
props.put("sasl.oauthbearer.client.credentials.client.secret", "your-client-secret");
props.put("sasl.oauthbearer.scope", "kafka:read kafka:write");

// Confluent Cloud extensions
props.put("sasl.jaas.config",
    "org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required "
    + "extension_logicalCluster=\"lkc-12345\" "
    + "extension_identityPoolId=\"pool-abcde\";");

// Timeout and retry settings
props.put("sasl.login.connect.timeout.ms", "10000");
props.put("sasl.login.read.timeout.ms", "10000");
props.put("sasl.login.retry.backoff.ms", "100");
props.put("sasl.login.retry.backoff.max.ms", "10000");

Configuration for Kafka client 4.0.x

The client credential properties aren’t available in Kafka client 4.0.x. Instead, set the client ID, client secret, and scope as options in sasl.jaas.config. Set the token endpoint URL with the sasl.oauthbearer.token.endpoint.url property, as in the previous example. For example:

Using String.join() (Java 8+):

String jaasConfig = String.join(" ",
    "org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required",
    "clientId=\"" + clientId + "\"",
    "clientSecret=\"" + clientSecret + "\"",
    "scope=\"" + scope + "\"",
    "extension_logicalCluster=\"" + logicalCluster + "\"",
    "extension_identityPoolId=\"" + identityPoolId + "\";"
);
props.put("sasl.jaas.config", jaasConfig);

Using Text Blocks (Java 15+):

String jaasConfig = """
    org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
    clientId="%s" \
    clientSecret="%s" \
    scope="%s" \
    extension_logicalCluster="%s" \
    extension_identityPoolId="%s";
    """.formatted(clientId, clientSecret, scope, logicalCluster, identityPoolId);
props.put("sasl.jaas.config", jaasConfig);

These JAAS options still work in Kafka client 4.1.0 and later, but they’re deprecated. When you upgrade, move them to the client credential properties.

Configuration example with client assertions

For client assertions, configure the client to authenticate to your identity provider with a signed JWT instead of a client secret. The client still uses the client_credentials grant type, and selects client assertion automatically when sasl.oauthbearer.assertion.file or sasl.oauthbearer.assertion.claim.iss is set. Client assertion support for the client_credentials grant type (KIP-1258) requires Kafka client 4.3.0 or later:

Properties props = new Properties();

// Basic Kafka configuration
props.put("bootstrap.servers", "your-bootstrap-server:9092");
props.put("security.protocol", "SASL_SSL");
props.put("sasl.mechanism", "OAUTHBEARER");
props.put("sasl.login.callback.handler.class",
    "org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginCallbackHandler");

// OAuth token endpoint
props.put("sasl.oauthbearer.token.endpoint.url", "https://identity-provider.com/oauth/token");

// Private key for signing assertions
props.put("sasl.oauthbearer.assertion.private.key.file", "/path/to/private-key.pem");
props.put("sasl.oauthbearer.assertion.algorithm", "RS256");

// Assertion claims
props.put("sasl.oauthbearer.assertion.claim.iss", "my-kafka-client");
props.put("sasl.oauthbearer.assertion.claim.sub", "my-service-account");
props.put("sasl.oauthbearer.assertion.claim.aud", "https://identity-provider.com");
props.put("sasl.oauthbearer.assertion.claim.exp.seconds", "300");

// Optional scope
props.put("sasl.oauthbearer.scope", "kafka.read kafka.write");

// JAAS configuration
props.put("sasl.jaas.config",
   "org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required "
   + "extension_logicalCluster=\"lkc-xxxxx\" "
   + "extension_identityPoolId=\"pool-xxxxx\";");

// Timeout and retry settings
props.put("sasl.login.connect.timeout.ms", "10000");
props.put("sasl.login.read.timeout.ms", "10000");
props.put("sasl.login.retry.backoff.ms", "100");
props.put("sasl.login.retry.backoff.max.ms", "10000");

Test your configuration

  1. Enable debug logging to troubleshoot OAuth issues:

    # Add to your configuration
    log4j.logger.org.apache.kafka.clients.NetworkClient=DEBUG
    log4j.logger.org.apache.kafka.common.security.oauthbearer=DEBUG
    
  2. Test with a simple producer:

    // Test producer
    KafkaProducer<String, String> producer = new KafkaProducer<>(props);
    ProducerRecord<String, String> record = new ProducerRecord<>("test-topic", "test-message");
    
    producer.send(record, (metadata, exception) -> {
        if (exception == null) {
            System.out.println("Message sent successfully - OAuth is working!");
        } else {
            System.err.println("Error sending message: " + exception.getMessage());
        }
        producer.close();
    });
    
  3. Check for common errors:

    • “SASL authentication failed” - Check your OAuth credentials and endpoint

    • “Invalid token” - Verify your OAuth configuration is correct

    • “Connection timeout” - Check your bootstrap servers and network connectivity

  4. Verify token refresh - The client should automatically refresh tokens when they expire

Configure Schema Registry Java clients

The Schema Registry Java client module includes support for the OpenID Connect (OIDC) authentication protocol and OAuth 2.0. This enables these Java clients to use token credentials to authenticate with Confluent Cloud Schema Registry.

To obtain the OAuth token, Schema Registry clients use the client credentials grant. The RFC client credential grant flow for obtaining authorization looks like this:

  1. The Schema Registry client makes a request to a public OIDC server or token server (for example, Okta), using the client ID and secret to authenticate with it.

  2. The OIDC server returns a token that the Schema Registry client can use to talk to the cloud Schema Registry server.

The logic of fetching tokens and providing them to HTTP headers in Schema Registry clients is done by the BearerAuthCredentialProvider (Token) Classes.

Before you configure a Schema Registry client for OAuth, ensure you have the following:

  • An io.confluent:kafka-schema-registry-client version that matches your kafka-clients version. The Schema Registry client’s OAuth support is built on the Kafka client’s OAuth classes, which changed between Kafka releases, so a mismatched pair can fail at runtime with a NoClassDefFoundError. Use the Schema Registry client from the Confluent Platform release that includes your Kafka client version. For example, use Schema Registry client 8.4.x with kafka-clients 4.4.x, and 8.1.x with kafka-clients 4.1.x. For the version mapping, see Supported Versions and Interoperability.

  • An identity pool with role bindings that grant access to the Schema Registry resources the client uses, such as subjects. OAuth authenticates the client, but the identity pool’s role bindings determine what it can do. For the Schema Registry roles, see Access control (RBAC) for Confluent Cloud Schema Registry. To add role bindings to an identity pool, see Add an OAuth identity pool.

  • If your application uses Kafka client 4.0.0 or later, the token endpoint URL in bearer.auth.issuer.endpoint.url added to the org.apache.kafka.sasl.oauthbearer.allowed.urls JVM system property. The Schema Registry client validates this URL with the same allowlist as the Kafka client.

Configure a Schema Registry client to use a standard OAuth authorization server and protocol

You can authenticate Schema Registry clients to a public OAuth 2.0 server by either adding the required configuration settings directly to the clients or by enabling the clients to inherit the settings.

To add OAuth authentication to Schema Registry, you must add the following configuration settings to your Schema Registry client:

// CachedSchemaRegistryClient accepts a Map<String, ?>, not Properties
Map<String, Object> srConfig = new HashMap<>();

// Schema Registry OAuth configuration
srConfig.put("bearer.auth.credentials.source", "OAUTHBEARER");
srConfig.put("bearer.auth.issuer.endpoint.url", "https://your-idp.com/oauth2/token");
srConfig.put("bearer.auth.client.id", "your-client-id");
srConfig.put("bearer.auth.client.secret", "your-client-secret");
srConfig.put("bearer.auth.scope", "schema:read schema:write");
srConfig.put("bearer.auth.logical.cluster", "lsrc-xxxxx");
srConfig.put("bearer.auth.identity.pool.id", "pool-xxxxx");

To inherit the OAuth configuration settings from your Kafka configuration, add the following settings to the same configuration that contains your Kafka OAuth settings. The Schema Registry client reads sasl.jaas.config and sasl.oauthbearer.token.endpoint.url from that configuration, so these settings don’t work in a separate configuration that contains only Schema Registry settings. For example, add them to the producer properties that you pass to KafkaProducer, which also configure the Schema Registry serializer:

// props contains the Kafka OAuth configuration shown in
// Configure Kafka Java clients, including sasl.jaas.config
props.put("schema.registry.url", "https://your-schema-registry-endpoint");

// Inherit OAuth configuration from Kafka client
props.put("bearer.auth.credentials.source", "SASL_OAUTHBEARER_INHERIT");
props.put("bearer.auth.logical.cluster", "lsrc-xxxxx");

If you don’t set bearer.auth.identity.pool.id, the Schema Registry client uses the extension_identityPoolId value from sasl.jaas.config.

If you connect to the Schema Registry private endpoint over AWS PrivateLink, you can omit bearer.auth.logical.cluster. For more information, see OAuth for Confluent Cloud Schema Registry REST API.

Configure a Schema Registry client to use a custom token provider and OAuth implementation

For custom OAuth implementations, use the following configuration:

bearer.auth.credentials.source=CUSTOM
bearer.auth.custom.provider.class=<fully-qualified-class-name>
bearer.auth.logical.cluster=<lsrc-resource-id>
bearer.auth.identity.pool.id=<identity-pool-id>

# Settings that your provider class reads in its configure() method.
# These keys are used by the example in Custom OAuth implementations.
custom.token.endpoint.url=<idp-token-endpoint-url>
custom.client.id=<oauth-client-id>
custom.client.secret=<oauth-client-secret>
custom.scope=<scope>

The bearer.auth.logical.cluster configuration is required for Confluent Cloud Schema Registry, except over AWS PrivateLink. It’s optional for other use cases.

The bearer.auth.identity.pool.id configuration is optional. If you omit bearer.auth.identity.pool.id, Confluent Cloud automatically maps the token to all identity pools whose filters match the token claims. For details, see Use auto pool mapping with OAuth identity pools.

The configurations above are for a Kafka producer. Other types of Schema Registry clients need appropriate prefixes. For example, KSQL would start with ksql.schema.registry.

Note

Resource Management Best Practice: When using Schema Registry clients, always use try-with-resources to ensure proper cleanup. The SchemaRegistryClient interface implements java.io.Closeable, so it can be used in a try-with-resources block for automatic cleanup:

try (SchemaRegistryClient schemaRegistryClient = new CachedSchemaRegistryClient(
    "https://your-schema-registry-endpoint",
    100, // cache capacity
    srConfig
)) {
    System.out.println("Schema Registry client configured successfully with OAuth.");
    // Use the client...
} catch (Exception e) {
    System.err.println("Error configuring Schema Registry client: " + e.getMessage());
}

Custom OAuth implementations

For advanced use cases, implement a custom token provider for the Schema Registry client. The provider class must meet these requirements:

  • Implement the io.confluent.kafka.schemaregistry.client.security.bearerauth.BearerAuthCredentialProvider interface, which extends org.apache.kafka.common.Configurable.

  • Have a public no-argument constructor. The Schema Registry client creates the provider through reflection, and then calls configure() with all of the client configuration settings, including any custom keys that you define. Read your settings in configure(), not in a constructor.

  • Return a token from getBearerToken() without throwing a checked exception. The Schema Registry client calls this method for every request, so cache the token and refresh it before it expires.

Set bearer.auth.custom.provider.class to the fully qualified class name, as shown in the configuration in Configure Schema Registry Java clients. The Schema Registry client adds the bearer.auth.logical.cluster and bearer.auth.identity.pool.id values to each request, so the provider only needs to return the token.

The following example requests a token from your identity provider with the client_credentials grant type. It reads the custom.* settings shown in the earlier configuration and requires Java 11 or later:

package com.example;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.confluent.kafka.schemaregistry.client.security.bearerauth.BearerAuthCredentialProvider;
import org.apache.kafka.common.config.ConfigException;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.Map;

public class CustomTokenProvider implements BearerAuthCredentialProvider {

    // Custom configuration keys. The Schema Registry client passes all of its
    // configuration settings to configure(), so you can define your own keys.
    public static final String TOKEN_ENDPOINT_URL = "custom.token.endpoint.url";
    public static final String CLIENT_ID = "custom.client.id";
    public static final String CLIENT_SECRET = "custom.client.secret";
    public static final String SCOPE = "custom.scope";

    // Refresh the token this long before it expires
    private static final Duration REFRESH_BUFFER = Duration.ofSeconds(60);

    private final HttpClient httpClient = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(10))
        .build();
    private final ObjectMapper mapper = new ObjectMapper();

    private URI tokenEndpoint;
    private String authorizationHeader;
    private String scope;

    private String cachedToken;
    private Instant refreshAt = Instant.MIN;

    // The Schema Registry client creates the provider with the public
    // no-argument constructor, and then calls configure().
    public CustomTokenProvider() {
    }

    @Override
    public void configure(Map<String, ?> configs) {
        tokenEndpoint = URI.create(required(configs, TOKEN_ENDPOINT_URL));
        String credentials = urlEncode(required(configs, CLIENT_ID)) + ":"
            + urlEncode(required(configs, CLIENT_SECRET));
        authorizationHeader = "Basic " + Base64.getEncoder()
            .encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
        Object scopeValue = configs.get(SCOPE);
        scope = scopeValue == null ? null : scopeValue.toString();
    }

    // Called for every Schema Registry request, so return a cached token and
    // request a new one only when the cached token is about to expire.
    @Override
    public synchronized String getBearerToken(URL url) {
        if (cachedToken == null || Instant.now().isAfter(refreshAt)) {
            fetchToken();
        }
        return cachedToken;
    }

    private void fetchToken() {
        String body = "grant_type=client_credentials";
        if (scope != null) {
            body += "&scope=" + urlEncode(scope);
        }
        HttpRequest request = HttpRequest.newBuilder(tokenEndpoint)
            .timeout(Duration.ofSeconds(10))
            .header("Content-Type", "application/x-www-form-urlencoded")
            .header("Authorization", authorizationHeader)
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        try {
            HttpResponse<String> response =
                httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() != 200) {
                throw new IllegalStateException("Token request failed with HTTP "
                    + response.statusCode() + ": " + response.body());
            }
            JsonNode json = mapper.readTree(response.body());
            JsonNode accessToken = json.get("access_token");
            if (accessToken == null) {
                throw new IllegalStateException("Token response has no access_token");
            }
            long expiresIn = json.path("expires_in").asLong(300);
            cachedToken = accessToken.asText();
            refreshAt = Instant.now().plusSeconds(expiresIn).minus(REFRESH_BUFFER);
        } catch (IOException e) {
            throw new UncheckedIOException("Token request failed", e);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IllegalStateException("Token request interrupted", e);
        }
    }

    private static String required(Map<String, ?> configs, String key) {
        Object value = configs.get(key);
        if (value == null || value.toString().isEmpty()) {
            throw new ConfigException("Missing required configuration: " + key);
        }
        return value.toString();
    }

    private static String urlEncode(String value) {
        return URLEncoder.encode(value, StandardCharsets.UTF_8);
    }
}

Google OIDC integration

Google doesn’t support the client_credentials grant type. To authenticate a Java client with a Google service account, use the jwt-bearer grant type, which requires Kafka client 4.1.0 or later. The client signs a JWT assertion with the service account’s private key and exchanges it at Google’s token endpoint for a Google-signed ID token, which the client then presents to Confluent Cloud.

Before you configure the client:

  • Add Google as an identity provider in Confluent Cloud by using the Other OIDC identity provider option with the OIDC discovery URL https://accounts.google.com/.well-known/openid-configuration. This sets the issuer URI to https://accounts.google.com and the JWKS URI to https://www.googleapis.com/oauth2/v3/certs. For details, see Add an OAuth/OIDC Identity Provider on Confluent Cloud.

  • Create a key for your Google service account, and save the private_key value from the downloaded JSON key file as a PEM file.

  • Create an assertion template file that sets the target_audience claim. Google returns an ID token, rather than an opaque access token, only when the assertion includes target_audience. The value becomes the aud claim of the ID token, which you can match in your identity pool filter:

    {
      "payload": {
        "target_audience": "your-kafka-audience"
      }
    }
    

Configure the client:

// Google service account configuration (jwt-bearer grant type)
Properties props = new Properties();
props.put("bootstrap.servers", "your-bootstrap-server:9092");
props.put("security.protocol", "SASL_SSL");
props.put("sasl.mechanism", "OAUTHBEARER");
props.put("sasl.login.callback.handler.class",
    "org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginCallbackHandler");
props.put("sasl.oauthbearer.token.endpoint.url", "https://oauth2.googleapis.com/token");
props.put("sasl.oauthbearer.jwt.retriever.class",
    "org.apache.kafka.common.security.oauthbearer.JwtBearerJwtRetriever");

// Assertion signed with the service account's private key
props.put("sasl.oauthbearer.assertion.algorithm", "RS256");
props.put("sasl.oauthbearer.assertion.private.key.file", "/path/to/service-account-key.pem");
props.put("sasl.oauthbearer.assertion.claim.iss",
    "your-service-account@your-project.iam.gserviceaccount.com");
props.put("sasl.oauthbearer.assertion.claim.aud", "https://oauth2.googleapis.com/token");
props.put("sasl.oauthbearer.assertion.template.file", "/path/to/assertion-template.json");

// Confluent Cloud extensions
props.put("sasl.jaas.config",
    "org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required "
    + "extension_logicalCluster=\"lkc-xxxxx\" "
    + "extension_identityPoolId=\"pool-xxxxx\";");

// Create producer with OAuth configuration
KafkaProducer<String, String> producer = new KafkaProducer<>(props);

Don’t set sasl.oauthbearer.scope or sasl.oauthbearer.assertion.claim.sub for this flow. The target_audience claim, not a scope, requests the ID token, and Google accepts a sub claim in the assertion only for domain-wide delegation.

Start the application with both the token endpoint and the files allowed:

java \
  -Dorg.apache.kafka.sasl.oauthbearer.allowed.urls=https://oauth2.googleapis.com/token \
  -Dorg.apache.kafka.sasl.oauthbearer.allowed.files=/path/to/service-account-key.pem,/path/to/assertion-template.json \
  -jar your-app.jar

Troubleshoot Java OAuth clients

Common issues and solutions for Java OAuth clients:

Authentication failures

  • Verify client ID and secret are correct

  • Check token endpoint URL is accessible

  • Ensure logical cluster ID is valid

  • Validate identity pool ID if used

Network issues

  • Confirm network connectivity to OAuth provider

  • Check firewall rules allow OAuth traffic

  • Verify SSL certificate validation

Configuration issues

  • Ensure all required parameters are provided

  • Validate OAuth configuration syntax

  • Check timeout values are reasonable

Dependency and startup errors

  • NoClassDefFoundError for a com.fasterxml.jackson class: Add the com.fasterxml.jackson.core:jackson-databind dependency. The kafka-clients artifact doesn’t include it as a transitive dependency.

  • ClassNotFoundException or NoClassDefFoundError for an org.jose4j class, wrapped in a KafkaException that says the client failed to construct the producer or consumer: Add the org.bitbucket.b_c:jose4j dependency. The kafka-clients artifact doesn’t include it as a transitive dependency.

  • NoClassDefFoundError for an org.apache.kafka.common.security.oauthbearer class when you use Schema Registry: Use a kafka-schema-registry-client version that matches your kafka-clients version. For details, see Configure Schema Registry Java clients.

  • ConfigException that says a URL or file isn’t allowed: Add the token endpoint URL to the org.apache.kafka.sasl.oauthbearer.allowed.urls JVM system property, and add any OAuth files to the org.apache.kafka.sasl.oauthbearer.allowed.files JVM system property. For details, see Configure Kafka Java clients.

Debug logging

Enable debug logging for OAuth troubleshooting:

# Enable OAuth debug logging
log4j.logger.org.apache.kafka.common.security.oauthbearer=DEBUG
log4j.logger.org.apache.kafka.clients.NetworkClient=DEBUG