如何配置Feign仅使用TLS1.3及指定加密套件?
Feign配置指定TLS版本、加密套件及全局授权头
要实现Feign的这两项配置,我们可以分两部分完成:自定义Feign的HTTP客户端管控TLS参数,通过请求拦截器统一添加授权头。
1. 配置Feign使用指定TLS版本和加密套件
Feign支持集成Apache HttpClient作为底层客户端,你可以复用之前的SSL配置逻辑,通过自定义HttpClient Bean关联Feign客户端配置来实现:
首先确保项目引入对应依赖(Spring Cloud场景下):
<!-- Spring Cloud Feign --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <!-- Feign Apache HttpClient 集成 --> <dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-httpclient</artifactId> </dependency>
然后创建Feign的SSL配置类:
import feign.httpclient.ApacheHttpClient; import org.apache.http.client.HttpClient; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import lombok.SneakyThrows; @Configuration public class FeignSslConfig { // 替换为你需要的TLS协议版本 private static final String[] SUPPORTED_PROTOCOLS = {"TLSv1.2"}; // 替换为你指定的加密套件列表 private static final String[] SUPPORTED_CIPHERS = {"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"}; @Bean public ApacheHttpClient feignHttpClient() { return new ApacheHttpClient(getCustomHttpClient()); } @SneakyThrows private HttpClient getCustomHttpClient() { var sslContext = SSLContext.getDefault(); var sslSocketFactory = new SSLConnectionSocketFactory( sslContext, SUPPORTED_PROTOCOLS, SUPPORTED_CIPHERS, javax.net.ssl.HttpsURLConnection.getDefaultHostnameVerifier() ); return org.apache.http.impl.client.HttpClients.custom() .setSSLSocketFactory(sslSocketFactory) .build(); } }
2. 全局添加授权头
通过Feign的RequestInterceptor可以为所有Feign请求统一添加授权头,创建如下配置类:
import feign.RequestInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class FeignAuthConfig { @Bean public RequestInterceptor authRequestInterceptor() { return requestTemplate -> { // 替换为你的授权头获取逻辑,比如从配置或上下文读取token String authToken = "Bearer your-access-token"; requestTemplate.header("Authorization", authToken); }; } }
如果需要针对单个FeignClient单独配置(而非全局生效),可以在FeignClient注解中指定配置类:
@FeignClient(name = "your-target-service", configuration = {FeignSslConfig.class, FeignAuthConfig.class}) public interface YourFeignClient { // 定义服务调用接口方法 }
完成以上配置后,你的Feign客户端就会使用指定的TLS版本和加密套件发起请求,同时自动携带授权头。
内容的提问来源于stack exchange,提问作者Datz
相关产品推荐
相关产品推荐

