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

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

/*
 * ----------------------------------------------------------------
 * © 2019-2021 SAP SE or an SAP affiliate company. All rights reserved.
 * ----------------------------------------------------------------
 *
 */
package com.sap.cds.mtx.impl;

import com.sap.cloud.security.client.DefaultHttpClientFactory;
import com.sap.cloud.security.config.OAuth2ServiceConfiguration;
import com.sap.cloud.security.xsuaa.client.DefaultOAuth2TokenService;
import com.sap.cloud.security.xsuaa.client.OAuth2TokenResponse;
import com.sap.cloud.security.xsuaa.client.XsuaaDefaultEndpoints;
import com.sap.cloud.security.xsuaa.tokenflows.TokenFlowException;
import com.sap.cloud.security.xsuaa.tokenflows.XsuaaTokenFlows;

import java.io.IOException;
import java.time.Instant;

/**
 * Class responsible for retrieval of a new JWT from XSUAA service via client
 * credential flow
 */
public class ClientCredentialJwtReader {
    private final XsuaaTokenFlows tokenFlows;

    /**
     * @param xsuaaParams parameters of xsuaa service instance
     */
    public ClientCredentialJwtReader(XsuaaParams xsuaaParams) {
        OAuth2ServiceConfiguration oAuth2ServiceConfiguration = xsuaaParams.getOAuth2ServiceConfiguration();
        DefaultHttpClientFactory clientFactory = new DefaultHttpClientFactory();
        tokenFlows = new XsuaaTokenFlows(new DefaultOAuth2TokenService(clientFactory.createClient(oAuth2ServiceConfiguration.getClientIdentity())),
                new XsuaaDefaultEndpoints(oAuth2ServiceConfiguration), oAuth2ServiceConfiguration.getClientIdentity());
    }

    /**
     * Retrieve a new JWT
     *
     * @return the {@link OAuth2TokenResponse}
     * @throws IOException thrown if communication with XSUAA service fails
     */
    public Response getJwt() throws IOException {
        try {
            OAuth2TokenResponse response = tokenFlows.clientCredentialsTokenFlow().execute();
            return new Response(response.getExpiredAt(), response.getAccessToken());
        } catch (TokenFlowException e) {
            throw new IOException("Could not retrieve JWT.", e);
        }
    }

    public static class Response {
        private final Instant expiredAt;
        private final String accessToken;

        public Response(Instant expiredAt, String accessToken) {
            this.expiredAt = expiredAt;
            this.accessToken = accessToken;
        }

        public boolean isValid() {
            return Instant.now().isBefore(expiredAt);
        }

        public String getAccessToken() {
            return accessToken;
        }

    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy