Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Cloud Feign with OAuth2RestTemplate

I'm trying to implement Feign Clients to get my user info from the user's service, currently I'm requesting with oAuth2RestTemplate, it works. But now I wish to change to Feign, but I'm getting error code 401 probably because it doesn't carry the user tokens, so there is a way to customize, if Spring support for Feign is using, a RestTemplate so I can use my own Bean?

Today I'm implementing in this way

The service the client

@Retryable({RestClientException.class, TimeoutException.class, InterruptedException.class})
@HystrixCommand(fallbackMethod = "getFallback")
public Promise<ResponseEntity<UserProtos.User>> get() {
    logger.debug("Requiring discovery of user");
    Promise<ResponseEntity<UserProtos.User>> promise = Broadcaster.<ResponseEntity<UserProtos.User>>create(reactorEnv, DISPATCHER)
            .observe(Promises::success)
            .observeError(Exception.class, (o, e) -> Promises.error(reactorEnv, ERROR_DISPATCHER, e))
            .filter(entity -> entity.getStatusCode().is2xxSuccessful())
            .next();
    promise.onNext(this.client.getUserInfo());
    return promise;

}

And the client

@FeignClient("account")
public interface UserInfoClient {

    @RequestMapping(value = "/uaa/user",consumes = MediaTypes.PROTOBUF,method = RequestMethod.GET)
    ResponseEntity<UserProtos.User> getUserInfo();
}
like image 466
Joao Evangelista Avatar asked Apr 03 '15 21:04

Joao Evangelista


2 Answers

Feign doesn't use a RestTemplate so you'd have to find a different way. If you create a @Bean of type feign.RequestInterceptor it will be applied to all requests, so maybe one of those with an OAuth2RestTemplate in it (just to manage the token acquisition) would be the best option.

like image 87
Dave Syer Avatar answered Sep 20 '22 23:09

Dave Syer


this is my solution, just to complement the another answer with the source code, implementing the interface feign.RequestInterceptor

@Bean
public RequestInterceptor requestTokenBearerInterceptor() {
    return new RequestInterceptor() {
        @Override
        public void apply(RequestTemplate requestTemplate) {
            OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)
                    SecurityContextHolder.getContext().getAuthentication().getDetails();

            requestTemplate.header("Authorization", "bearer " + details.getTokenValue());
        }
    };
}
like image 29
Rafael Zeffa Avatar answered Sep 17 '22 23:09

Rafael Zeffa