Spring Cloud Feign with OAuth2RestTemplate

故事扮演 提交于 2019-12-30 00:41:27

问题


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();
}

回答1:


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.




回答2:


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());
        }
    };
}


来源:https://stackoverflow.com/questions/29439653/spring-cloud-feign-with-oauth2resttemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!