【问题标题】:How to call a rest service with client certificate using the feign client如何使用 feign 客户端调用带有客户端证书的休息服务
【发布时间】:2019-07-11 07:54:41
【问题描述】:

我想访问受客户端证书保护的休息服务。如果提供了正确的证书,服务器只会接受请求。我们在项目中使用 Feign 客户端,但我找不到解决此问题的示例。是否添加为拦截器?

【问题讨论】:

    标签: client-certificates feign


    【解决方案1】:

    这个问题可以通过如下创建自定义 Feign 配置来解决:

    class CustomFeignConfiguration {
    
        private val log = Logger.getLogger(this.javaClass.name)
    
        @Value("\${client_p12_base64_encoded_string}")
        private val clientP12: String = ""
    
        @Value("\${client_p12_password}")
        private val clientP12Pass: String = ""
    
        @Bean
        fun feignClient(): Client {
            val sslSocketFactory= getSSLSocketFactory()
            log.info("CUSTOM FEIGN CLIENT CALLED")
            return Client.Default(sslSocketFactory, DefaultHostnameVerifier())
        }
    
        private fun getSSLSocketFactory(): SSLSocketFactory {
            val decoder = java.util.Base64.getDecoder()
            val p12 = decoder.decode(clientP12)
            val p12File = File("clientCer.p12")
            p12File.writeBytes(p12)
    
            try {
                val sslContext = SSLContexts
                    .custom()
                    .loadKeyMaterial(p12File, clientP12Pass.toCharArray(), clientP12Pass.toCharArray())
                    .build()
                return sslContext.socketFactory
            } catch (exception: Exception) {
                throw RuntimeException(exception)
            }
    
        }
    }
    

    使用配置的FeignClient接口必须专门加载这个

    @FeignClient(name = "client", configuration = [CustomFeignConfiguration::class], url = "\${url}")
    interface Client {
      ....
      ....
    }
    

    SSLContexts 库只能使用 p12 证书,我们必须将 PEM 格式的证书和密钥转换为 P12 格式。

    使用以下 SSL 命令从您的 PEM 证书和密钥创建 p12 证书:

    openssl pkcs12 -export -inkey domain.key -in domain.crt -out domain.p12
    

    请记录您在运行此命令后输入的密码。

    使用以下命令将此 p12 证书转换为 base64 字符串

    base64 domain.p12 > domain.p12.base64
    

    使用以下命令将此多行字符串转换为单行字符串:

    tr -d "\n\r" < domain.p12.base64 > domain.p12.base64.singleline
    

    使用此命令中的单行字符串和您之前在 application.properties 中记录的密码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-23
      • 2016-03-09
      • 1970-01-01
      • 1970-01-01
      • 2020-10-23
      • 2019-11-18
      • 2014-08-17
      • 1970-01-01
      相关资源
      最近更新 更多