Search code examples
spring-cloudspring-cloud-netflixspring-oauth2

spring oauth and client credentials M2M calls


I have a front end website that is secured using spring-cloud-secuirty with spring-cloud-oauth2 . All my backend resources are secured using @EnableResourceServer .

All requests to these resources services coming from UI are authorized through the Zuul gateway, but my problem is with back end tasks that are scheduled to run on daily bases or the one are triggered by email. These tasks are not authorized and as I understood from reading they should be authenticated as client_credentials . But i am not able to figure out how to configure feign clients to get the access code before trying to communicate with secured resources.

I have created a sample project , in this project every thing is working except the task service


Solution

  • Adding the below interceptor did the trick but i am not sure this is the best solution

    @Component
    public class Interceptor implements RequestInterceptor {
    
        private final OAuth2RestTemplate template;
    
        public Interceptor(ClientCredentialsResourceDetails oauth2RemoteResource) {
          template = new OAuth2RestTemplate(oauth2RemoteResource, new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()));
        }
    
        @Override
        public void apply(RequestTemplate requestTemplate) {
            requestTemplate.header("Authorization", "bearer " + template.getAccessToken().getValue());
        }
    }
    

    Better Approach

    After more reading I found that spring-cloud-security already have an interceptor so we just need to declare a bean of type OAuth2FeignRequestInterceptor as below

    @Configuration
    @EnableOAuth2Client
    @Slf4j
    public class OAuth2FeignAutoConfiguration {
    
        @Bean
        public OAuth2FeignRequestInterceptor oAuth2FeignRequestInterceptor(OAuth2ClientContext oauth2ClientContext, OAuth2ProtectedResourceDetails details) {
            return new OAuth2FeignRequestInterceptor(oauth2ClientContext,details);
        }
    
    
    }