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

com.dnastack.audit.auth.AccessTokenDelegate Maven / Gradle / Ivy

package com.dnastack.audit.auth;

import brave.Tracing;
import com.dnastack.audit.client.AuthHttpClient;
import com.dnastack.audit.model.AuditEventLoggerConfig;
import com.dnastack.audit.model.TokenResponse;
import interceptor.TokenDelegate;
import lombok.extern.slf4j.Slf4j;

import java.time.Duration;
import java.time.Instant;
import java.util.Objects;

@Slf4j
public class AccessTokenDelegate implements TokenDelegate {

    private final static Duration TOKEN_VALIDITY_BUFFER = Duration.ofSeconds(60);
    private final AuthHttpClient authHttpClient;
    private TokenResponse tokenResponse;
    private Instant tokenRetrievedAt;

    public AccessTokenDelegate(AuditEventLoggerConfig.OAuthClient oAuthClientConfig, Tracing tracing) {
        Objects.requireNonNull(oAuthClientConfig);
        oAuthClientConfig.validate();
        this.authHttpClient = new AuthHttpClient(oAuthClientConfig, tracing);
    }

    @Override
    public String getCurrentToken() {
        return getAccessToken();
    }

    @Override
    public String getNewToken() {
        refreshAccessToken();
        return getAccessToken();
    }

    /**
     * NOTE on synchronization: This is to prevent calling refreshAccessToken() if getAccessToken() is called in rapid succession
     *
     * If thread which calls getAccessToken() acquires class level lock then it's eligible to call refreshAccessToken() as well
     *
     * @return access token
     */
    private synchronized String getAccessToken() {
        if (tokenResponse == null) {
            refreshAccessToken();
        } else if (tokenRetrievedAt.plusSeconds(tokenResponse.getExpiryInSeconds()).minus(TOKEN_VALIDITY_BUFFER).isBefore(Instant.now())) {
            log.debug("Access token has expired, or will be expiring within the buffer window. Refreshing token now");
            refreshAccessToken();
        }
        return tokenResponse.getAccessToken();
    }

    /**
     * NOTE on synchronization: This is to prevent calling auth server if refreshAccessToken() is called in rapid succession
     */
    private synchronized void refreshAccessToken() {
        tokenResponse = authHttpClient.getTokenResponse();
        tokenRetrievedAt = Instant.now();
        log.debug("Successfully retrieved access token");
    }

}





© 2015 - 2025 Weber Informatics LLC | Privacy Policy