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

com.c4_soft.springaddons.rest.ReactiveAuthorizedClientBearerProvider Maven / Gradle / Ivy

There is a newer version: 7.9.0-M4
Show newest version
package com.c4_soft.springaddons.rest;

import java.util.List;
import java.util.Optional;

import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.core.OAuth2AccessToken;

import lombok.Data;
import lombok.EqualsAndHashCode;
import reactor.core.publisher.Mono;

/**
 * A {@link ClientHttpRequestInterceptor} adding a Bearer Authorization header (if the {@link OAuth2AuthorizedClientManager} provides one for the configured
 * registration ID).
 *
 * @author Jerome Wacongne ch4mp@c4-soft.com
 */
@Data
@EqualsAndHashCode(callSuper = false)
public class ReactiveAuthorizedClientBearerProvider implements ReactiveBearerProvider {
    private static final AnonymousAuthenticationToken ANONYMOUS = new AnonymousAuthenticationToken(
        "anonymous",
        "anonymous",
        List.of(new SimpleGrantedAuthority("ROLE_ANONYMOUS")));

    private final ReactiveOAuth2AuthorizedClientManager authorizedClientManager;
    private final String registrationId;

    @Override
    public Mono getBearer() {
        final var authentication = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication()).orElse(ANONYMOUS);
        OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(registrationId).principal(authentication).build();
        final var authorizedClient = authorizedClientManager.authorize(authorizeRequest);
        final var token = authorizedClient.map(OAuth2AuthorizedClient::getAccessToken);
        return token.map(OAuth2AccessToken::getTokenValue);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy