All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sap.cds.mtx.impl.ClientCredentialJwtAccess Maven / Gradle / Ivy

Go to download

Tools for http service communication and resilience usable by all libs of multi-tenancy and CAP

There is a newer version: 3.3.3
Show newest version
/*
 * ----------------------------------------------------------------
 * © 2019-2021 SAP SE or an SAP affiliate company. All rights reserved.
 * ----------------------------------------------------------------
 *
 */
package com.sap.cds.mtx.impl;

import com.google.common.annotations.VisibleForTesting;

import java.io.IOException;
import java.util.Optional;

/**
 * Class providing access to JWT tokens, a retrieved JWT is cached until it
 * expires
 */
public class ClientCredentialJwtAccess implements Authenticator {
    private static final String AUTHENTIFICATION_SCHEME = "Bearer";

    private final ClientCredentialJwtReader jwtReader;
    // response is buffered as long as JWT is valid
    private volatile ClientCredentialJwtReader.Response response; //NOSONAR

    /**
     * @param jwtReader object that retrieves a new JWT from XSUAA
     */
    public ClientCredentialJwtAccess(ClientCredentialJwtReader jwtReader) {
        this.jwtReader = jwtReader;
    }

    /**
     * Returns a valid JWT
     *
     * @return the JWT as string
     * @throws IOException
     */
    @VisibleForTesting
    String getJwt() throws IOException {
        // see double checked locking for this pattern
        ClientCredentialJwtReader.Response localRef = response;
        if (localRef == null || !localRef.isValid()) {
            synchronized (this) {
                localRef = response;
                if (localRef == null || !localRef.isValid()) {
                    response = localRef = jwtReader.getJwt();
                }
            }
        }

        return localRef.getAccessToken();
    }

    @Override
    public Optional getAuthorization() throws IOException {
        return Optional.of(AUTHENTIFICATION_SCHEME + " " + getJwt());
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy