Search code examples
spring-bootspring-securityoauth-2.0netflix-zuulspring-cloud-feign

Spring boot Oauth2 : Token relay from a client using Feign, Ribbon, Zull and Eureka to a ressource


I have an oauth2 client that get a token from an authorization server successfully. (not always has been the case but now it is... :))

The client, the zuul gateway and the resource server are all registered in Eureka.

My client use a Proxy to access to a remote ressource service named microservice-files.

@RestController
@FeignClient(name = "zuul-server")
@RibbonClient(name = "microservice-files")

public interface ProxyMicroserviceFiles {

    @GetMapping(value = "microservice-files/root")
    FileBean getUserRoot();

}

So I'd like to relay the token to Zull and then to the resource server.

I can relay the token this way to contact Zuul and apparently the load balancing is managed too (I've just test I didn't know and it's great) also zuul can relay the token, but it's not very convenient I'd prefer the previous approach.

@EnableConfigurationProperties
@SpringBootApplication
@EnableFeignClients("com.clientui")
public class ClientUiApplication {

    @Bean
    public OAuth2RestOperations restOperations(
            OAuth2ProtectedResourceDetails resource, 
            OAuth2ClientContext context) {

        return new OAuth2RestTemplate(resource, context);
    }

    public static void main(String[] args) {

        SpringApplication.run(ClientUiApplication.class, args);
    }
}

here is the test controler

@Controller
public class ClientController {

    @Autowired
    private RestOperations restOperations;

    @RequestMapping("/root")
    public ResponseEntity userRootTest() {

       String rootUrl = "http://localhost:9004/microservice-files/root";

       return  restOperations.getForEntity(rootUrl,FileBean.class);

    }

}

Solution

  • If I correctly understand your problem then you can use a RequestInterceptor to add a token in each request by the feign. In order to do it you can use the next configuration:

    @Bean
    public RequestInterceptor oauth2FeignRequestInterceptor(OAuth2ClientContext oauth2ClientContext,
                                                            OAuth2ProtectedResourceDetails resource) {
        return new OAuth2FeignRequestInterceptor(oauth2ClientContext, resource);
    }
    
    @Bean
    protected OAuth2ProtectedResourceDetails resource() {
        AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails();
        resource.setAccessTokenUri("http://127.0.0.1:9000/auth/login");
        resource.setUserAuthorizationUri("http://127.0.0.1:9000/auth/authorize");
        resource.setClientId("my-client");
        resource.setClientSecret("my-secret");
        return resource;
    }