如何使用SSL配置Spring RestTemplate(在Spring @MVC中)

时间:2011-10-27 09:20:31

标签: spring spring-security resttemplate

我想使用 SSL 配置 Spring @MVC 存根应用程序的 Spring RestTemplate ,以便与 REST 基础进行通信部署在 Tomcat 服务器(Spring 3,Tomcat 7)上的 https 应用程序。我已经完成了refer this link的作品。现在我不知道如何将这些生成的证书 Spring RestTemplate 一起使用,任何人都有一些想法请帮帮我。谢谢。到目前为止我做过的事情,

// Spring Security xml配置

   <http>
    <intercept-url pattern="/login" access="IS_AUTHENTICATED_ANONYMOUSLY" requires-channel="https"/>      
    <http-basic/></http> 

//使用Tomcat启用SSL的配置

<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol" maxThreads="200"
    scheme="https" secure="true" SSLEnabled="true"
    keystoreFile="C:\Users\Channa\.keystore" keystorePass="changeit"
    clientAuth="false" sslProtocol="TLS"/>

用于生成密钥,证书等,

//生成客户端和服务器密钥:

F:\ jdk1.6.0_23 \ bin&gt; keytool -genkey -keystore keystore_client -alias clientKey -dname“CN = localhost,OU = Dev,O = MyBusiness,L = Colombo,S = Westen,C = SL”<登记/> F:\ jdk1.6.0_23 \ bin&gt; keytool -genkey -keystore keystore_server -alias serverKey -dname“CN = localhost,OU = Dev,O = MyBusiness,L = Colombo,S = Westen,C = SL”

//生成客户端和服务器证书:

F:\ jdk1.6.0_23 \ bin&gt; keytool -export -alias clientKey -rfc -keystore keystore_client&gt; client.cert F:\ jdk1.6.0_23 \ bin&gt; keytool -export -alias serverKey -rfc -keystore keystore_server&gt; server.cert

//将证书导入相应的信任库:

F:\ jdk1.6.0_23 \ bin&gt; keytool -import -alias clientCert -file client.cert -keystore truststore_server F:\ jdk1.6.0_23 \ bin&gt; keytool -import -alias serverCert -file server.cert -keystore truststore_client

// Spring RestTemplate配置

    

<!--Http client-->
<bean id="httpClient" class="org.apache.commons.httpclient.HttpClient">
    <constructor-arg ref="httpClientParams"/>
    <property name="state" ref="httpState"/>
</bean>

<!--Http state-->
<bean id="httpState" class="com.org.imc.test.stub.http.CustomHttpState">
    <property name="credentials" ref="usernamePasswordCredentials"/>
</bean>

<!--User name password credentials-->
<bean id="usernamePasswordCredentials" class="org.apache.commons.httpclient.UsernamePasswordCredentials"/>

<!--Http client-->
<bean id="httpClientFactory" class="org.springframework.http.client.CommonsClientHttpRequestFactory">
    <constructor-arg ref="httpClient"/>
</bean>

<!--RestTemplate-->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
    <constructor-arg ref="httpClientFactory"/>
</bean>

// Https URL即可访问

ResponseEntity<User> rECreateUser = restTemplate.postForEntity("https://127.0.0.1:8443/skeleton-1.0/login", user, User.class);

//目前有例外:

org.springframework.web.client.ResourceAccessException:I / O错误:sun.security.validator.ValidatorException:PKIX路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到所请求目标的有效证书路径;嵌套异常是javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到所请求目标的有效证书路径

3 个答案:

答案 0 :(得分:7)

这是因为您正在呼叫的服务的SSL证书未由受信任的证书颁发机构签名。解决方法是将证书导入JRE的证书信任库(cacerts)。

  1. 通过在浏览器中打开URL来下载证书,然后单击锁定 浏览器地址栏中的图标。
  2. 获得.cer文件后,执行以下命令

    keytool -import -keystore jdk1.8.0_77/jre/lib/security/cacerts -file ~/test.cer -alias test
    

答案 1 :(得分:2)

您可以使用Apache HttpComponents HttpClient中的HttpComponentsClientHttpRequestFactory配置RestTemplate,它肯定支持SSL。

参考:Does REST (RestTemplate) in Spring Library support HTTPS protocol?

答案 2 :(得分:0)

Variant for Spring Boot:

  1. 添加依赖项:

     implementation 'org.apache.httpcomponents:httpclient:4.5'    
    
  2. 提供RestTemplate bean:

@Bean
private RestTemplate restTemplate() {
        SSLContext sslContext = buildSslContext();
        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);

        HttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(socketFactory)
                .build();

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);

        return new RestTemplate(factory);
    }

private SSLContext buildSslContext() {
        try {
            char[] keyStorePassword = sslProperties.getKeyStorePassword();
            return new SSLContextBuilder()
                    .loadKeyMaterial(
                            KeyStore.getInstance(new File(sslProperties.getKeyStore()), keyStorePassword),
                            keyStorePassword
                    ).build();
        } catch (Exception ex) {
            throw new IllegalStateException("Unable to instantiate SSL context", ex);
        } finally {
            sslProperties.setKeyStorePassword(null);
            sslProperties.setTrustStorePassword(null);
        }
    }
  1. 在application.properties或application.yaml文件中提供必需的SSL属性:
server:
    ssl:
        enabled: true
        key-store: /path/to/key.keystore
        key-store-password: password
        key-alias: alias
        trust-store: /path/to/truststore
        trust-store-password: password

就是这样。现在,您可以看到Tomcat在8080(或其他端口)(https)上启动。 或者,您可以使用my spring boot starter