使用Spring RestTemplate访问Https Rest服务 [英] Access Https Rest Service using Spring RestTemplate

查看:1469
本文介绍了使用Spring RestTemplate访问Https Rest服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以向我提供一个代码示例,以使用spring rest模板访问使用https保护的rest服务url。



我有证书,用户名和密码。基本身份验证在服务器端使用,我想创建一个客户端,可以使用提供的证书,用户名和密码(如果需要)连接到该服务器。

解决



我需要创建一个自定义的 ClientHttpRequestFactory 以信任证书。它看起来像这样:

  final ClientHttpRequestFactory clientHttpRequestFactory = 
new MyCustomClientHttpRequestFactory(org.apache.http.conn.ssl。 SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER,serverInfo);
restTemplate.setRequestFactory(clientHttpRequestFactory);

这是 MyCustomClientHttpRequestFactory 的实现:

  public class MyCustomClientHttpRequestFactory extends SimpleClientHttpRequestFactory {

private final HostnameVerifier hostNameVerifier;
private final ServerInfo serverInfo;

public MyCustomClientHttpRequestFactory(final HostnameVerifier hostNameVerifier,
final ServerInfo serverInfo){
this.hostNameVerifier = hostNameVerifier;
this.serverInfo = serverInfo;
}

@Override
protected void prepareConnection(final HttpURLConnection connection,final String httpMethod)
throws IOException {
if(HttpsURLConnection的连接实例){
((HttpsURLConnection)connection).setHostnameVerifier(hostNameVerifier);
((HttpsURLConnection)connection).setSSLSocketFactory(initSSLContext()
.getSocketFactory());
}
super.prepareConnection(connection,httpMethod);
}

private SSLContext initSSLContext(){
try {
System.setProperty(https.protocols,TLSv1);

//设置ssl信任管理器。验证我们的服务器指纹
final SSLContext ctx = SSLContext.getInstance(TLSv1);
final SslThumbprintVerifier verifier = new SslThumbprintVerifier(serverInfo);
final ThumbprintTrustManager thumbPrintTrustManager =
new ThumbprintTrustManager(null,verifier);
ctx.init(null,new TrustManager [] {thumbPrintTrustManager},null);
return ctx;
} catch(final Exception ex){
LOGGER.error(
尝试初始化HTTP安全管理器时抛出异常,ex);
return null;
}
}

在这种情况下,我的 serverInfo 对象包含服务器的指纹。您需要实现 TrustManager 接口以获取 SslThumbprintVerifier 或任何其他您要验证证书的方法(您可以也决定也总是返回 true )。



org.apache.http。 conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER 允许所有主机名。如果您需要验证主机名,您需要以不同的方式实现它。



我不确定用户和密码以及如何实现它,但通常您需要向 restTemplate 添加一个标题授权,其值类似于 Base:< encoded user + password> ,用户+密码需要 Base64 编码。


Can anybody provide me with a code sample to access rest service url secured with https using spring rest template.

I have the certificate, username and password. Basic Authentication is used on the server side and I want to create a client that can connect to that server using provided certificate, username and password (if needed).

解决方案

I'm adding here code that Will give you the general idea.

You need to create a custom ClientHttpRequestFactory in order to trust the certificate. It looks like this:

final ClientHttpRequestFactory clientHttpRequestFactory =
        new MyCustomClientHttpRequestFactory(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER, serverInfo);
    restTemplate.setRequestFactory(clientHttpRequestFactory);

This is the implementation for MyCustomClientHttpRequestFactory:

public class MyCustomClientHttpRequestFactory  extends SimpleClientHttpRequestFactory {

private final HostnameVerifier hostNameVerifier;
private final ServerInfo serverInfo;

public MyCustomClientHttpRequestFactory (final HostnameVerifier hostNameVerifier,
    final ServerInfo serverInfo) {
    this.hostNameVerifier = hostNameVerifier;
    this.serverInfo = serverInfo;
}

@Override
protected void prepareConnection(final HttpURLConnection connection, final String httpMethod)
    throws IOException {
    if (connection instanceof HttpsURLConnection) {
        ((HttpsURLConnection) connection).setHostnameVerifier(hostNameVerifier);
        ((HttpsURLConnection) connection).setSSLSocketFactory(initSSLContext()
            .getSocketFactory());
    }
    super.prepareConnection(connection, httpMethod);
}

private SSLContext initSSLContext() {
    try {
        System.setProperty("https.protocols", "TLSv1");

        // Set ssl trust manager. Verify against our server thumbprint
        final SSLContext ctx = SSLContext.getInstance("TLSv1");
        final SslThumbprintVerifier verifier = new SslThumbprintVerifier(serverInfo);
        final ThumbprintTrustManager thumbPrintTrustManager =
            new ThumbprintTrustManager(null, verifier);
        ctx.init(null, new TrustManager[] { thumbPrintTrustManager }, null);
        return ctx;
    } catch (final Exception ex) {
        LOGGER.error(
            "An exception was thrown while trying to initialize HTTP security manager.", ex);
        return null;
    }
}

In this case my serverInfo object contained the thumbprint of the server. You need to implement the TrustManager interface to get the SslThumbprintVerifier or any other method you want to verify your certificate (you can also decide to also always return true).

The org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER allows all host name. If you need to verify the host name you'd need to implement it differently.

I'm not sure about the user and password and how you implemented it, but usually you need to add a header to the restTemplate that is named Authorization and its value looks like Base: <encoded user+password> and the user + password need to be Base64 encoded.

这篇关于使用Spring RestTemplate访问Https Rest服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆