我想你可以试试。
在我的项目中,我们还使用OAuth2、Eureka和Ribbon来实现微服务之间的通信。为了在OAuth2中使用Ribbon,我们采用的方法有些不同。
首先我们保持rest模板不变。
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
但是,我们创建了实现RequestIntercepter的FeignClientIntercepter,它在通过restemplate发出请求时为OAuth设置授权令牌。
@Component
public class UserFeignClientInterceptor implements RequestInterceptor {
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String BEARER_TOKEN_TYPE = "Jwt";
@Override
public void apply(RequestTemplate template) {
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
if (authentication != null && authentication
.getDetails() instanceof OAuth2AuthenticationDetails) {
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication
.getDetails();
template.header(AUTHORIZATION_HEADER,
String.format("%s %s", BEARER_TOKEN_TYPE, details.getTokenValue()));
}
}
}
外国客户
而不是REST模板。
@FeignClient("your-project-name")
public interface YourProjectClient {
@GetMapping("your-endpoint")
JsonObject getSomething();