DEV Community

Igor Rudel
Igor Rudel

Posted on • Edited on

4

Spring Boot + Feign Client + OAuth2

Esse post está sendo criado baseando-se na versão 3.3.3 do Spring Boot.

As dependências do Feign e OAuth utilizadas:

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

<dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-oauth2-client</artifactId>
</dependency>
Enter fullscreen mode Exit fullscreen mode

Se você possui um microserviço que tem a necessidade de consumir outras api's que possuem authenticação OAuth2 com token JWT Bearer o Feign precisa ser configurado para solicitar um token válido para uso nas requisições.

Para isso é necessário a definição de 2 propriedades e consequentemente o Feign condiciona a necessidade de outras 3 beans para o contexto do Spring.

As duas propriedades são:

spring.cloud.openfeign.oauth2.enabled
spring.cloud.openfeign.oauth2.clientRegistrationId
Enter fullscreen mode Exit fullscreen mode

As beans são:

OAuth2AuthorizedClientService
ClientRegistrationRepository
OAuth2AuthorizedClientManager
Enter fullscreen mode Exit fullscreen mode

Como fiz a configuração de um realm em um Keycloak local com aquisição de token via client_credentials.

As propriedades locais ficaram:

spring.cloud.openfeign.oauth2.enabled=true
spring.cloud.openfeign.oauth2.clientRegistrationId=default

# As propriedades abaixo são customizadas para manter padrão e utilizar no mesmo contexto

spring.cloud.openfeign.oauth2.client-id=first-client
spring.cloud.openfeign.oauth2.client-secret=BFcymx4a7UH86FrHPUxei0SPKHSoRDSW
spring.cloud.openfeign.oauth2.token-uri=http://localhost:8080/realms/first-realm/protocol/openid-connect/token
Enter fullscreen mode Exit fullscreen mode

As beans de configuração:

    @Value("${spring.cloud.openfeign.oauth2.clientRegistrationId}")
    private String registrationId;

    @Value("${spring.cloud.openfeign.oauth2.client-id}")
    private String clientId;

    @Value("${spring.cloud.openfeign.oauth2.client-secret}")
    private String clientSecret;

    @Value("${spring.cloud.openfeign.oauth2.token-uri}")
    private String tokenUri;

    @Bean
    ClientRegistrationRepository clientRegistrationRepository() {
        var clientRegistration = ClientRegistration.withRegistrationId(registrationId)
            .clientId(clientId)
            .clientSecret(clientSecret)
            .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
            .tokenUri(tokenUri)
            .build();

        return new InMemoryClientRegistrationRepository(clientRegistration);
    }

    @Bean
    OAuth2AuthorizedClientService oAuth2AuthorizedClientService(final ClientRegistrationRepository clientRegistrationRepository) {
        return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository);
    }

    @Bean
    OAuth2AuthorizedClientRepository oAuth2AuthorizedClientRepository(final OAuth2AuthorizedClientService oAuth2AuthorizedClientService) {
        return new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(oAuth2AuthorizedClientService);
    }

    @Bean
    OAuth2AuthorizedClientManager authorizedClientManager(final ClientRegistrationRepository clientRegistrationRepository,
                                                          final OAuth2AuthorizedClientRepository oAuth2AuthorizedClientRepository) {
        return new DefaultOAuth2AuthorizedClientManager(clientRegistrationRepository, oAuth2AuthorizedClientRepository);
    }
Enter fullscreen mode Exit fullscreen mode

Para facilitar a visualização nos log's das requisições para outra api:

@Configuration
public class CustomFeingConfig {

    @Bean
    Logger.Level loggerLevel() {
        return Logger.Level.BASIC; //FULL
    }
}
Enter fullscreen mode Exit fullscreen mode
logging.level.br.xksoberbado=DEBUG
Enter fullscreen mode Exit fullscreen mode

Para facilitar a visualização nos log's das requisições da aquisição do token:

logging.level.org.springframework.web.client=DEBUG
Enter fullscreen mode Exit fullscreen mode

Link do projeto (api-two) no GitHub: https://github.com/oigorrudel/spring-oauth2-example

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay