welcome to xlongwei.com

欢迎大家一起学习、交流、分享


QQ群:162333776 邮箱:admin@xlongwei.com

https 安全协议配置


分类 Server   关键字 分享   标签 web   linux   nginx   发布 hongwei  1462804510741
注意 转载须保留原文链接,译文链接,作者译者等信息。  
https方式访问网络时数据是加密传输的,因此可以更好地保护交易数据以及用户隐私信息。api接口服务也最好支持https方式,才能更好地保护接口调用数据。nginx的proxy_redirect指令支持将https请求代理给http方式的服务端程序,统一配置还是非常方便的。

server {
listen 443 ssl;
server_name api.xlongwei.com;
access_log /var/log/nginx/access.log main;
ssl_certificate /soft/cert/1_xlongwei.com_bundle.crt; //WoSign CA免费证书,相当于公钥,浏览器会自动安装证书
ssl_certificate_key /soft/cert/2_xlongwei.com.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
location / {
proxy_pass http://127.0.0.1:80;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header SSL '1';
proxy_redirect http:// https://;
}
}

Java代码访问https接口
//以下代码见ServiceRequester
public static CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setMaxConnTotal(maxConnTotal)
.setMaxConnPerRoute(maxConnPerRoute)
.setUserAgent("ServiceRequester / HttpClient 4.3")
.setSslcontext(FileUtil.sslContext) //不设置此项时会抛异常
.build();

//以下代码见FileUtil
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] arg0,String arg1) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] arg0,String arg1) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() { return null; }
}
}, null);

下载https文件,见FileUtil
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) { return true; }
});

测试请求:
https://api.xlongwei.com/service/datetime.json