Cloud Security

SAP XSUAA Token Client: Secure Token Flows in Cloud Apps

May 21, 2026 · 11 min read · By William do Carmo
SAP XSUAA Token Client: Secure Token Flows in Cloud Apps

The com.sap.cloud.security.xsuaa:token-client library is a focused Java component within the broader SAP Cloud Security Services Integration Library. Its sole responsibility is abstracting the complexity of OAuth 2.0 token acquisition against the XSUAA (Cross-Site User Account and Authentication) service on SAP Business Technology Platform. For security engineers and DevSecOps teams operating multi-service landscapes on SAP BTP, understanding how this library manages credentials, handles token refresh, and integrates with mutual TLS is essential for building defensible cloud-native architectures.

Where the Token Client Fits in the SAP Security Stack

The SAP Cloud Security Services Integration Library is a monorepo that provides several distinct capabilities: a servlet filter for request-level security, a Spring Security integration layer, a testing utility for mocking XSUAA bindings in unit tests, and the standalone token-client module. The token-client is deliberately decoupled from any specific web framework. It operates as a programmatic HTTP client that communicates with the XSUAA token endpoint, handling client authentication, grant-type parameterization, and token caching without requiring Spring Boot or any other framework on the classpath. This separation matters in polyglot microservice environments where not every service is a Spring application, and where lightweight Java services or command-line tools still need to obtain access tokens for service-to-service calls.

Supported OAuth 2.0 Grant Types

The library implements three core grant types that map to the most common communication patterns in SAP BTP deployments. The client_credentials grant is used for service-to-service communication where no end-user context is involved. The password grant, while generally discouraged by modern OAuth guidance, is supported for backward compatibility with certain SAP legacy integration scenarios. The user_token grant (also called the JWT bearer grant, or grant type urn:ietf:params:oauth:grant-type:jwt-bearer) enables token exchange: a service receives a token on behalf of an end user and exchanges it for a new token scoped for a downstream service. This is the critical flow for propagating user identity across microservice boundaries without exposing user credentials at any intermediate hop.

Each grant type is exposed through a dedicated builder or factory method, making it difficult to accidentally select the wrong flow at compile time. The library also enforces that the client_id and client_secret extracted from the VCAP_SERVICES environment binding are passed to the correct authentication header construction, preventing misconfigured token requests that could leak credentials in query parameters.

Client Authentication Methods and Credential Handling

By default, the token client uses the HTTP Basic authentication scheme to present the client_id and client_secret to the XSUAA token endpoint. This is the standard approach prescribed by RFC 6749 for confidential clients. The library reads these credentials from the XSUAA service binding available at runtime via the VCAP_SERVICES environment variable, parsing the JSON structure to extract the relevant fields without requiring developers to handle raw environment variable parsing in application code.

For environments where client secrets are prohibited, the token client supports certificate-based client authentication using X.509 certificates. In this mode, the library presents a client certificate during the TLS handshake with the XSUAA endpoint, and the server authenticates the client based on the certificate rather than a shared secret. The SAP Cloud SDK documentation describes this mutual TLS (mTLS) approach as ensuring that both client and server verify each other’s identities by use of X.509 certificates before any HTTP exchange proceeds. The token client integrates with this by accepting a configured SSL context that carries the client certificate, delegating the TLS negotiation to the underlying HTTP client while still managing the OAuth grant-type payload.

Token Caching and Refresh Strategy

Token acquisition is an HTTP round-trip with non-trivial latency, and XSUAA tokens have a configurable lifetime (typically 15 minutes to 1 hour depending on the service plan). The token-client includes an in-memory cache that stores acquired tokens keyed by their grant-type parameters and scopes. When a cached token is available and has not expired (the library checks the exp claim and applies a configurable skew buffer to avoid edge-case expiration), the cached token is returned without any network call.

The cache is not distributed or persistent. In a horizontally scaled deployment with multiple application instances, each instance maintains its own independent token cache. This is generally acceptable because the cost of a few redundant token requests during instance startup or cache invalidation is negligible compared to the complexity of a distributed cache for a short-lived artifact. However, teams operating at very high scale with frequent instance cycling should be aware that a cold cache on a new instance will trigger a token request on the first call, which can cause a latency spike if many instances start simultaneously.

Integrating with Mutual TLS via SAP Cloud SDK

The token client can be used in isolation, but in practice many SAP BTP applications also depend on the SAP Cloud SDK for connectivity, resilience, and destination handling. When mTLS is required, the Cloud SDK provides a certificate-based authentication flow where the client certificate is provisioned through a binding to the XSUAA service plan that supports certificate credentials. The token client consumes the resulting ClientIdentity object, which wraps the certificate and private key, and uses it to construct an SSL context that is injected into the underlying HTTP client.

This integration path eliminates client secrets entirely from the runtime environment. For compliance-sensitive workloads subject to regulatory frameworks that mandate secretless authentication, combining the token client with mTLS bindings provides a defensible architecture where the only credential material is a certificate that never travels over the wire in plaintext and can be rotated through the BTP service binding lifecycle without application code changes.

Security Hardening Recommendations for DevSecOps Teams

While the token client handles much of the OAuth protocol correctly by design, the surrounding application configuration determines whether the integration is actually secure in practice. The following ordered list represents the priority hardening steps that DevSecOps pipelines should enforce:

  1. Audit grant-type usage. Ensure that only client_credentials and user_token grants are in active use. Flag any occurrence of the password grant in code review and require explicit justification with a documented migration plan.
  2. Restrict scopes to the minimum necessary. The token client accepts scope parameters that limit the resulting token’s permissions. Every service-to-service token request should specify explicit scopes rather than requesting all scopes available to the bound XSUAA client.
  3. Migrate to mTLS bindings. For any service in a compliance-regulated scope, replace client-secret-based authentication with certificate-based client authentication using the XSUAA certificate credential binding.
  4. Validate token responses. Although the token client trusts the XSUAA endpoint, defense-in-depth demands that consuming code validates the token’s iss, aud, exp, and scope claims before using it for authorization decisions.
  5. Rotate binding credentials. Automate XSUAA service key rotation in CI/CD pipelines and verify that the token client correctly picks up new credentials on instance restart without manual intervention.

Common Pitfalls in Multi-Service Architectures

The most frequent misconfiguration involves scope propagation during token exchange. When a service receives a user token and uses the user_token grant to obtain a new token for a downstream service, the resulting token’s scopes are determined by the intersection of the original token’s scopes, the requesting service’s XSUAA client grants, and any explicitly requested scopes. If the downstream service expects a scope that the intermediate service was not granted, the token exchange succeeds but the downstream authorization check fails with a generic 403. Diagnosing this requires tracing the scope chain across three XSUAA client configurations, which is non-trivial without centralized logging.

Another recurring issue arises from mixing the token-client library with manual HTTP calls to the XSUAA endpoint in the same application. When developers bypass the library for one integration and use it for another, the manual call may not implement the same caching, error handling, or credential parsing logic, leading to inconsistent behavior under load or after credential rotation. The library’s GitHub repository explicitly recommends using the token-client module to avoid cumbersome setup for HTTP requests, and teams should enforce this as a coding standard rather than allowing ad-hoc OAuth implementations.

Testing and Mocking XSUAA Interactions

The parent integration library includes a dedicated testing module that provides mock implementations of the XSUAA token endpoint. This allows unit and integration tests to exercise token-client code paths without requiring a live XSUAA instance or real service bindings. The mock returns well-formed JWT tokens with configurable claims, enabling tests to verify scope validation logic, token caching behavior, and error handling for expired or invalid tokens.

In CI/CD pipelines, the testing utility should be combined with environment profiles that substitute the real XSUAA endpoint URL with the mock endpoint. This prevents accidental token requests to production or staging XSUAA instances from test suites running in ephemeral build environments that lack proper service bindings. For end-to-end tests that must validate real token flows, use a dedicated XSUAA instance in an isolated development space with service keys that are automatically provisioned and torn down as part of the pipeline lifecycle.

Compliance Mapping to Cloud Security Frameworks

The Cloud Security Alliance framework, informed by both ENISA and NIST work, emphasizes identity-based security controls as foundational to cloud risk management. The token client’s support for scoped access tokens, certificate-based authentication, and token exchange directly addresses several control families within that framework. Specifically, the ability to enforce least-privilege through scoped tokens aligns with access control requirements, while mTLS integration addresses authentication assurance requirements for service-to-service communication in shared-responsibility cloud models.

For teams mapping SAP BTP security controls to internal compliance matrices, the token client should be documented as the standardized mechanism for OAuth 2.0 token acquisition. Any deviation, such as direct HTTP calls or third-party OAuth client libraries, introduces uncontrolled variance that auditors will flag as a gap in identity management standardization.

Comparative Overview of Token Client Capabilities

CapabilityClient CredentialsJWT Bearer (User Token)Password Grant
Use caseService-to-service, no userPropagate user context downstreamLegacy system integration
Client auth (default)HTTP Basic (client_id/secret)HTTP Basic (client_id/secret)HTTP Basic (client_id/secret)
Client auth (mTLS)Supported via SSL contextSupported via SSL contextNot applicable
Token cachingIn-memory, keyed by scopesIn-memory, keyed by user tokenIn-memory, keyed by credentials
Recommended statusPreferred for system callsPreferred for user propagationDeprecate when possible

FAQ

Does the token client validate the JWT tokens it receives from XSUAA?

No. The token client’s responsibility ends at acquiring the token from the XSUAA endpoint and caching it. JWT validation (signature verification, issuer check, expiration, audience) must be performed by a separate component, typically the security filter from the parent integration library or the Spring Security integration, depending on your application’s architecture.

Can I use the token client outside of Spring Boot?

Yes. The token-client module has no dependency on Spring or any other web framework. It can be used in plain Java applications, command-line tools, scheduled jobs, or any JVM-based service that has access to the XSUAA service binding environment variables.

What happens if the XSUAA endpoint is unreachable?

The token client throws a TokenFlowException (or a subclass thereof) wrapping the underlying HTTP connection error. It does not implement retry logic internally. If you need resilience features such as retries with exponential backoff, you should wrap the token client call with a resilience library such as Resilience4j or use the SAP Cloud SDK’s built-in resilience decorators.

How does the token client handle credential rotation?

The token client reads credentials from the XSUAA service binding at the point of each token request (or from the cached binding object). If the service binding is updated in the BTP environment and the application instance is restarted, the new credentials are picked up automatically. For zero-downtime rotation, the new and old credentials are both valid for a overlap period defined by XSUAA, so a rolling restart of application instances will switch to the new credentials without service interruption.

Is the in-memory token cache safe in a multi-threaded environment?

Yes. The cache implementation is thread-safe and uses concurrent data structures internally. Multiple threads can request tokens simultaneously without risking cache corruption or duplicate token requests for the same cache key within the same expiration window.

Sources