SAP BTP Security Services Integration Library

repository·main·Indexed 41 days ago

https://github.com/sap/cloud-security-services-integration-library

A set of Java libraries for simplifying OAuth 2.0 token validation and retrieval for applications on SAP BTP using XSUAA and Identity Services. Version 4.1.2 includes the java-security client library for Jakarta EE token validation and the java-security-test library for offline JUnit testing with WireMock, JwtGenerator, and an embedded Jetty server.

Tokens
44.6K
Snippets
116
Records
184
Agent score
51%

What's inside SAP BTP Security Services Integration Library

  1. Overview of SAP BTP Spring Security Client Library

    main

    The SAP BTP Spring Security Client Library provides token validation for Spring Boot applications using tokens issued by SAP BTP Identity service or XSUAA. It integrates java-security with Spring Security OAuth 2.0 Resource Server to provide:

    • Automatic OAuth2 service configuration: Automatically configures services based on SAP BTP service bindings found in the environment.
    • OAuth2 Token Validation: Validates tokens using the discovered service configurations.
    • Claim Access: Provides easy access to principal and token claims within request handlers.
    • Token Retrieval: Supports fetching XSUAA tokens using various Grant types.

    Supported Environments:

    • Cloud Foundry
    • Kubernetes/Kyma

    Supported Identity Services:

    • SAP Identity service (supports Multitenancy/multiple zones)
    • XSUAA

    Supported JWS Algorithms:

    • RS256 (RSA256: RSASSA-PKCS1-v1_5 with SHA-256)
  2. Overview of SAP BTP Java Security Client Library

    main

    The SAP BTP Java Security Client Library is a Token Validation utility designed for Jakarta EE applications. It supports tokens issued by SAP BTP Identity services (including multi-tenant/multiple zone scenarios) and XSUAA services.

    Core Functionalities

    • Configuration Loading: Automatically loads Identity Service Configuration from VCAP_SERVICES (Cloud Foundry) or secrets (Kubernetes) into OAuth2ServiceConfiguration via the Environments entry point.
    • Token Parsing: Decodes and parses JSON Web Tokens (JWT) into Token objects, providing access to header parameters and claims (RFC 7519).
    • Token Validation: Uses JwtValidatorBuilder to assemble validators for Xsuaa or Identity services. Validation includes:
      • Timestamp: Checks exp (expiration) and nbf (not before) claims.
      • Issuer: Validates the JWT was issued by a trustworthy identity service (Identity service only).
      • JKU: Validates the jku header parameter points to a valid JWKS URL matching the uaadomain (Xsuaa only).
      • Audience: Checks the aud claim to ensure the token is intended for the application.
      • Signature: Verifies the signature using the public key of the identity service.
    • Context Management: Stores validated tokens in a thread-local cache called SecurityContext.
  3. Overview of SAP BTP Java Security Test Library

    main

    The java-security-test library provides utilities for writing JUnit tests for applications secured with java-security, spring-security, or spring-security-3 without requiring a real SAP BTP Identity or XSUAA service instance.

    It achieves this by:

    1. Starting a WireMock server on localhost pre-configured with stubbed responses for JWKS and OIDC endpoints.
    2. Providing a JwtGenerator to create custom JSON Web Tokens (JWTs) signed with keys that match the stubbed JWKS.
    3. Offering an optional Jetty application server for Java EE applications, pre-configured with a security filter that only accepts valid tokens.

    This allows for offline, local testing of both Spring Boot and Java EE security layers.

  4. Overview of XSUAA Token Client and Token Flow API

    main

    The XSUAA Token Client is a lightweight HTTP client designed to interact with Xsuaa /oauth/token and /token_keys endpoints. It provides the XsuaaTokenFlows class to programmatically manage various OAuth2 token flows within a Java application.

    Supported token flows include:

    • Jwt Bearer Token Flow: Used for principal propagation by exchanging a service-specific JWT for a new access token (e.g., exchanging a token for Service A to get a token for Service B).
    • Client Credentials Flow: Used by non-interactive applications (CLI, batch jobs, service-to-service) to acquire an access token without a user context.
    • Refresh Token Flow: Used to obtain a new access token when the current one is expired or invalid.
    • Password Token Flow: Uses resource owner credentials (username/password) to obtain an access token (requires high trust).

    Note: The Authorization Code Grant Flow is typically handled by an API gateway (like an Application Router) and is not the primary focus of this programmatic client.

  5. Overview of SAP BTP Security Services Integration Libraries

    main

    The SAP BTP Security Services Integration Libraries provide tools to simplify integrating SAP Business Technology Platform (SAP BTP) security services (XSUAA and Identity Services) into Java applications.

    Key capabilities include:

    • OAuth 2.0 Token Validation: Streamlined validation for tokens issued by XSUAA and Identity Services.
    • Token-Client Library: Easily fetch tokens for HTTP requests without complex manual setup.
    • Testing Utilities: Mocking of XSUAA and Identity service behaviors for unit and integration testing.

    Important Constraint: These libraries are designed and tested exclusively for SAP BTP (Cloud Foundry and Kubernetes/Kyma). They rely on service bindings and environment discovery (Environments.getCurrent()) provided by the SAP BTP runtime. Usage in other environments (on-premise, other clouds) is not supported.

  6. Understand the Spring Security Hybrid Sample Application

    main

    This Spring Boot sample application demonstrates how to use the spring-security module to validate JWT tokens from two different sources:

    1. XSUAA Service: Provides OAuth access tokens.
    2. Identity (IAS) Service: Provides OIDC tokens.

    Even though the token claims differ between these services, the validated token is consistently accessible as a Token via the Spring org.springframework.security.core.context.SecurityContextHolder.

    The sample also demonstrates the CorrelationIdFilter, which:

    • Appends a correlation_id to the MDC context.
    • Uses that ID to augment outgoing requests with an X-CorrelationID header.
  7. Use the embedded Jetty Application Server

    main

    For Java EE applications, you can start an embedded Jetty server via .useApplicationServer() in your Rule or Extension.

    Key features:

    • Security: It is pre-configured with a TokenAuthenticator that blocks requests (HTTP 401) if they do not contain a valid JWT from the JwtGenerator.
    • Servlet Mounting: Servlets mapped in web.xml are mounted automatically. For annotation-based servlets, use .addApplicationServlet(Class, path) to mount them manually.
    • Filters: You can add custom filters using .addApplicationServletFilter(...) to test specific routes based on roles or scopes.
  8. Perform a user token flow using token-client

    main

    Unlike the deprecated (XS)UserInfo methods which automatically handled token information, the token-client library decouples the flow from the token.

    When performing a user token flow (an exchange flow), you must explicitly pass the existing user token to the token method.

    • If you are already using the new API, obtain the token via getTokenValue().
    • If you are still using the deprecated (XS)UserInfo, obtain the token via getAppToken().
  9. How token exchange for hybrid authentication works

    main

    In hybrid authentication setups, your application can accept tokens from both SAP Identity Authentication Service (IAS) and XSUAA simultaneously. This allows users to authenticate via IAS while the application continues to use XSUAA-based authorization (scopes/roles).

    Workflow

    1. Request arrives with Authorization: Bearer <token>.
    2. Library identifies the issuer (IAS vs XSUAA) from token claims.
    3. Token is validated against the appropriate service.
    4. If IAS token + exchange enabled: The library obtains an IAS ID token, calls the XSUAA /oauth/token endpoint using a JWT bearer grant, and stores the exchanged XSUAA token in the SecurityContext.
    5. If exchange disabled or XSUAA token: The validated token is used directly.

    Constraints

    • IAS User Tokens Only: Exchange only applies to end-user tokens. Client credentials (technical) tokens are not exchanged.
    • Performance: Exchanged tokens are automatically cached per request until expiration.

    Prerequisites

    1. Both XSUAA and IAS service bindings must be configured.
    2. The IAS service binding must include the parameter xsuaa-cross-consumption: true.
    3. XSUAA must trust the IAS identity provider.
  10. Validate JWT tokens in Spring WebFlux applications

    main

    In a Spring WebFlux (reactive) application, the standard autoconfiguration for JwtDecoder only works for Servlet-based applications. To use the resourceserver-security-spring-boot-3-starter in a reactive environment, you must implement a manual SecurityConfiguration to configure the reactive JWT decoder and authentication converter.

    Once validated, the token is accessible as a Token via the ReactiveSecurityContext.

  11. Implement a custom HTTP client using HttpRequestExecutor

    main

    The token-client library uses Java 11 HttpClient by default. If you require advanced features like proxy configurations, custom connection pooling, mTLS, or specific retry logic, you can provide a custom implementation by implementing the HttpRequestExecutor interface and wrapping it in a CustomHttpClientAdapter.

    @FunctionalInterface
    public interface HttpRequestExecutor {
        HttpResponse execute(URI uri, String method, Map<String, String> headers, byte[] body)
            throws HttpClientException;
    }