-
编写配置类
@Slf4j public class OAuth2FeignConfiguration {@Value("${auth.server.access-token-uri}")private String accessTokenUri;@Value("${auth.server.client-id}")private String clientId;@Value("${auth.server.client-secret}")private String clientSecret;@Value("${auth.server.host}")private String host;public OAuth2ClientContext oAuth2ClientContext = new DefaultOAuth2ClientContext();@Beanpublic ErrorDecoder errorDecoder() {return (methodKey, response) -> {if (response.status() == HttpStatus.UNAUTHORIZED.value()) {oAuth2ClientContext.setAccessToken(null);throw new RetryableException(response.status(), "access_token expire, retry", response.request().httpMethod(), new Date());}String message = response.reason();try {message = IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8);} catch (IOException e) {log.error("error decode error: {}", e);}return new RuntimeException("[" + methodKey + "], status: " + response.status() + ", message: " + message);};}@Beanpublic Retryer feignRetryer() {return new Retryer.Default(100, SECONDS.toMillis(1), 2);}@BeanRequestInterceptor oauth2FeignRequestInterceptor() {return new OAuth2FeignInterceptor(oAuth2ClientContext, resource(), host);}private ClientCredentialsResourceDetails resource() {ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails();resource.setAccessTokenUri(accessTokenUri);resource.setClientId(clientId);resource.setClientSecret(clientSecret);return resource;} }
-
自定义:OAuth2FeignRequestInterceptor
@Slf4j class OAuth2FeignInterceptor extends OAuth2FeignRequestInterceptor {private final String target;public OAuth2FeignInterceptor(OAuth2ClientContext oAuth2ClientContext, OAuth2ProtectedResourceDetails resource, String target) {super(oAuth2ClientContext, resource);this.target = target;}@Overridepublic void apply(RequestTemplate template) {if (StringUtils.isNotEmpty(target)) {template.target(target);}super.apply(template);} }
-
编写测试类
@FeignClient(name = "hello-service", configuration = OAuth2FeignConfiguration.class ) public interface HelloFeignClient {@GetMapping("/hello/index/{userId}")UserInfo index(@PathVariable("userId") String userId); }