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

driven-adapter.cognito-token-provider.reactive.cognito-token-provider.mustache Maven / Gradle / Ivy

Go to download

Gradle plugin to create a clean application in Java that already works, It follows our best practices!

There is a newer version: 3.20.10
Show newest version
package {{package}}.cognito;

import {{package}}.cognito.model.CognitoCredentials;
import {{package}}.cognito.model.CognitoTokenResponse;
import {{package}}.model.gateway.TokenProvider;
{{#lombok}}
import lombok.extern.log4j.Log4j2;
{{/lombok}}
import org.springframework.http.HttpStatusCode;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.time.Duration;

{{#lombok}}
@Log4j2
{{/lombok}}
public class CognitoTokenProvider implements TokenProvider {
{{^lombok}}
    private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(CognitoTokenProvider.class);
{{/lombok}}
    public static final int COGNITO_RETRIES = 3;
    private final Mono cachedToken;

    public CognitoTokenProvider(WebClient client, Mono credentialsProvider) {
        this.cachedToken = credentialsProvider
                .flatMap(credentials ->
                        client.post()
                                .body(BodyInserters.fromFormData("grant_type", "client_credentials")
                                        .with("client_id", credentials.getClientId())
                                        .with("client_secret", credentials.getClientSecret()))
                                .retrieve()
                                .onStatus(HttpStatusCode::isError, response -> response.bodyToMono(String.class)
                                        .map(IOException::new))
                                .bodyToMono(CognitoTokenResponse.class)
                                .retry(COGNITO_RETRIES))
                .doOnError(err -> log.warn("Error calling cognito", err))
                .cache(this::cacheTime, error -> Duration.ZERO, () -> Duration.ZERO)
                .map(CognitoTokenResponse::getAccessToken);
        }

    @Override
    public Mono getToken() {
        return cachedToken;
    }

    private Duration cacheTime(CognitoTokenResponse token) {
        log.info("Generated from cognito and expires in: {} seconds and will be refreshed in: {} seconds",
                token.getExpiresIn(), token.getCacheTime());
        return Duration.ofSeconds(token.getCacheTime());
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy