在Javaclient中将@FeignClient与OAuth2Authentication一起使用

时间:2019-08-13 10:29:03

标签: spring-boot spring-cloud spring-cloud-feign

我想在简单的Spring Boot应用程序(CommandLineRunner)中使用@FeignClient来调用微服务端点。如何提供OAuth2Authentication来调用受保护的端点,例如helloUser()

@FeignClient(name = "sampleService", contextId = "greetingService")
public interface GreetingService {

    @GetMapping("/hello-anonymous")
    String helloAnonymous();


    @GetMapping("/hello-user")
    @Secured({ Role.USER })
    String helloUser();


    @GetMapping("/hello-admin")
    @Secured({ Role.ADMIN })
    String helloAdmin();
}

1 个答案:

答案 0 :(得分:1)

您可以使用伪装RequestInterceptor将auth标头传递到下游:

public class FeignRequestInterceptor implements RequestInterceptor {


    @Override
    public final void apply(RequestTemplate template) {
        template.header("Authorization", "foo token");
    }
}

这样,所有伪装呼叫都将配备一个auth标头。