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

com.adobe.pdfservices.operation.internal.auth.ServicePrincipalAuthenticator Maven / Gradle / Ivy

/*
 * Copyright 2024 Adobe
 * All Rights Reserved.
 *
 * NOTICE: Adobe permits you to use, modify, and distribute this file in
 * accordance with the terms of the Adobe license agreement accompanying
 * it. If you have received this file from a source other than Adobe,
 * then your use, modification, or distribution of it requires the prior
 * written permission of Adobe.
 */
package com.adobe.pdfservices.operation.internal.auth;

import com.adobe.pdfservices.operation.auth.ServicePrincipalCredentials;
import com.adobe.pdfservices.operation.internal.GlobalConfig;
import com.adobe.pdfservices.operation.internal.InternalClientConfig;
import com.adobe.pdfservices.operation.internal.constants.RequestKey;
import com.adobe.pdfservices.operation.internal.dto.response.AuthenticationResponseDto;
import com.adobe.pdfservices.operation.internal.http.BaseHttpRequest;
import com.adobe.pdfservices.operation.internal.http.DefaultRequestHeaders;
import com.adobe.pdfservices.operation.internal.http.HttpClient;
import com.adobe.pdfservices.operation.internal.http.HttpClientFactory;
import com.adobe.pdfservices.operation.internal.http.HttpMethod;
import com.adobe.pdfservices.operation.internal.http.HttpRequest;
import com.adobe.pdfservices.operation.internal.http.HttpRequestConfig;
import com.adobe.pdfservices.operation.internal.http.HttpResponse;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class ServicePrincipalAuthenticator implements Authenticator {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServicePrincipalAuthenticator.class);
    private static String IMS_PROXY_TOKEN_ENDPOINT = "token";
    private static String TOKEN_ENDPOINT;
    private static final String CLIENT_ID = "client_id";
    private static final String CLIENT_SECRET = "client_secret";

    private ServicePrincipalCredentials servicePrincipalCredentials;
    private SessionToken sessionToken;

    public ServicePrincipalAuthenticator(ServicePrincipalCredentials servicePrincipalCredentials,
                                         InternalClientConfig clientConfig) {
        this.servicePrincipalCredentials = servicePrincipalCredentials;
        TOKEN_ENDPOINT = String.format("%s/%s", clientConfig.getPdfServiceUri(), IMS_PROXY_TOKEN_ENDPOINT);
    }

    @Override
    public SessionToken getSessionToken(HttpRequestConfig requestConfig) {
        if (sessionToken != null) {

            // Check expiration token with a 2 minute buffer
            Duration durationTillSessionExpiry = Duration.between(Instant.now(), sessionToken.getExpiresAt());
            if (durationTillSessionExpiry.getSeconds() > 0 && durationTillSessionExpiry.toMinutes() > 2) {
                LOGGER.debug("Session Token is valid, won't be refreshed. ");
                return sessionToken;
            } else {
                LOGGER.debug("Session token expired. Refreshing! ");
            }
        }
        return refreshSessionToken(requestConfig);
    }

    @Override
    public SessionToken refreshSessionToken(HttpRequestConfig requestConfig) {
        HttpClient client = HttpClientFactory.getDefaultHttpClient();

        // The auth request must never require any authentication
        HttpRequest httpRequest = new BaseHttpRequest(SESSION_TOKEN_REQUEST_GROUP_KEY, HttpMethod.POST,
                                                      TOKEN_ENDPOINT).withAuthenticationMethod(AuthenticationMethod.UNAUTHENTICATED)
                .withHeader(DefaultRequestHeaders.DC_REQUEST_ID_HEADER_KEY, UUID.randomUUID().toString())
                .withHeader(DefaultRequestHeaders.DC_APP_INFO_HEADER_KEY, GlobalConfig.getAppInfo())
                .withHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString())
                .withUrlEncodedFormParams(getFormParams()).withRequestKey(RequestKey.IMS_PROXY)
                .withConfig(requestConfig);

        HttpResponse sessionTokenResponse = client.send(httpRequest,
                                                                                   AuthenticationResponseDto.class);
        AuthenticationResponseDto authResponseBody = sessionTokenResponse.getBody();


        sessionToken = new SessionToken(authResponseBody.getAccessToken(), Instant.now()
                .plusSeconds(authResponseBody.getExpiryInterval()));

        return sessionToken;
    }

    @Override
    public String getClientId() {
        return servicePrincipalCredentials.getClientId();
    }

    private List getFormParams() {
        List formParams = new ArrayList<>();
        formParams.add(new BasicNameValuePair(CLIENT_ID, servicePrincipalCredentials.getClientId()));
        formParams.add(new BasicNameValuePair(CLIENT_SECRET, servicePrincipalCredentials.getClientSecret()));
        return formParams;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy