SpringLDAP連接LDAPS證書報錯問題及解決
一、問題背景
Java操作LDAP一般通過Spring LDAP比較方便,一般我們都是使用的常規(guī)的非加密的389端口
常規(guī)的初始化如下:
LdapContextSource contextSource = new LdapContextSource(); contextSource.setUserDn(config.getUsername()); contextSource.setPassword(config.getPassword()); String url = "ldap://" + config.getServer() + ":" + config.getPort(); contextSource.setUrl(url); contextSource.setBase(config.getBaseDn()); contextSource.setAnonymousReadOnly(false); contextSource.setPooled(false); contextSource.afterPropertiesSet(); this.ldapTemplate = new LdapTemplate(contextSource); this.ldapTemplate.setIgnorePartialResultException(true);
但是最近遇到一個使用證書加密環(huán)境的LDAP,即LDAPS(LDAP+SSL),使用的是636端口,再使用上述的配置,則會報錯,可能會報以下的未找到合法證書的錯誤:
simple bind failed: 172.16.10.2:636; nested exception is javax.naming.CommunicationException: simple bind failed: 172.16.10.2:636 [Root exception is javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target]
二、解決方案
一般我們在Java使用HTTPS客戶端的時候為了避免證書報錯,一般會將客戶端證書導(dǎo)入到JDK中,但是有些環(huán)境的證書是自簽名的證書,導(dǎo)入也不一定能解決問題。
因此多數(shù)也會通過X509TrustManager和SSLSocketFactory繞過證書校驗,所以我們對于LDAPS也采用同樣的思路來解決,網(wǎng)上有類似的解決方案,但是集成之后可能還是存在以下的報錯:
org.springframework.ldap.CommunicationException: simple bind failed: 172.16.10.2:636; nested exception is javax.naming.CommunicationException: simple bind failed: 172.16.10.2:636 [Root exception is javax.net.ssl.SSLHandshakeException: No subject alternative names matching IP address 172.16.10.2 found]
at org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:108)
at org.springframework.ldap.core.support.AbstractContextSource.createContext(AbstractContextSource.java:355)
at org.springframework.ldap.core.support.AbstractContextSource.doGetContext(AbstractContextSource.java:139)
at org.springframework.ldap.core.support.AbstractContextSource.getReadOnlyContext(AbstractContextSource.java:158)
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:357)
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:309)
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:642)
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:578)
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:1617)
simple bind failed: XXXXX.com:636; nested exception is javax.naming.CommunicationException: simple bind failed: XXXXX.com:636 [Root exception is javax.net.ssl.SSLHandshakeException: No subject alternative DNS name matching XXXXX.com found.]
org.springframework.ldap.CommunicationException: simple bind failed: 172.16.10.2:636; nested exception is javax.naming.CommunicationException: simple bind failed: 172.16.10.2:636 [Root exception is java.net.SocketException: Connection or outbound has closed]
at org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:108)
at org.springframework.ldap.core.support.AbstractContextSource.createContext(AbstractContextSource.java:355)
at org.springframework.ldap.core.support.AbstractContextSource.doGetContext(AbstractContextSource.java:139)
at org.springframework.ldap.core.support.AbstractContextSource.getReadOnlyContext(AbstractContextSource.java:158)
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:357)
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:309)
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:642)
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:578)
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:1617)
我的解決方案分為以下幾個步驟,能規(guī)避以上錯誤:
(1)自定義SSLSocketFactory
package com.bugdongdong.utils.tools.ldap;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class CustomSSLSocketFactory extends SSLSocketFactory {
private SSLSocketFactory socketFactory;
public CustomSSLSocketFactory() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{new DummyTrustmanager()}, new SecureRandom());
socketFactory = ctx.getSocketFactory();
} catch (Exception ex) {
ex.printStackTrace(System.err);
}
}
public static SocketFactory getDefault() {
return new CustomSSLSocketFactory();
}
@Override
public String[] getDefaultCipherSuites() {
return socketFactory.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return socketFactory.getSupportedCipherSuites();
}
@Override
public Socket createSocket(Socket socket, String string, int num, boolean bool) throws IOException {
return socketFactory.createSocket(socket, string, num, bool);
}
@Override
public Socket createSocket(String string, int num) throws IOException, UnknownHostException {
return socketFactory.createSocket(string, num);
}
@Override
public Socket createSocket(String string, int num, InetAddress netAdd, int i) throws IOException, UnknownHostException {
return socketFactory.createSocket(string, num, netAdd, i);
}
@Override
public Socket createSocket(InetAddress netAdd, int num) throws IOException {
return socketFactory.createSocket(netAdd, num);
}
@Override
public Socket createSocket(InetAddress netAdd1, int num, InetAddress netAdd2, int i) throws IOException {
return socketFactory.createSocket(netAdd1, num, netAdd2, i);
}
/**
* 繞過證書校驗
*/
public static class DummyTrustmanager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] cert, String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] cert, String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
}
(2)自定義支持SSL的SSLContextSource
package com.bugdongdong.utils.tools.ldap;
import org.springframework.ldap.core.support.LdapContextSource;
import javax.naming.Context;
import java.util.Hashtable;
public class SSLLdapContextSource extends LdapContextSource {
public Hashtable<String, Object> getAnonymousEnv(){
// 禁用jdk8以上對ldap的端點校驗
System.setProperty("com.sun.jndi.ldap.object.disableEndpointIdentification", "true");
Hashtable<String, Object> anonymousEnv = super.getAnonymousEnv();
anonymousEnv.put("java.naming.security.protocol", "ssl");
anonymousEnv.put("java.naming.ldap.factory.socket", CustomSSLSocketFactory.class.getName());
anonymousEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
return anonymousEnv;
}
}
(3)構(gòu)建支持SSL的LdapTemplate
// 普通ldap連接使用普通的Context配置
LdapContextSource contextSource = new LdapContextSource();
String url = "";
if (DataSourceLdapConfig.TRANSPORT_TYPE_CLEAR.equals(config.getTransportType())) {
url = "ldap://" + config.getServer() + ":" + config.getPort();
} else if (DataSourceLdapConfig.TRANSPORT_TYPE_LDAPS.equals(config.getTransportType())) {
url = "ldaps://" + config.getServer() + ":" + config.getPort();
// ldaps使用自定義的支持SSL的Context配置
contextSource = new SSLLdapContextSource();
}
contextSource.setUserDn(config.getUsername());
contextSource.setPassword(config.getPassword());
contextSource.setUrl(url);
contextSource.setBase(config.getBaseDn());
contextSource.setAnonymousReadOnly(false);
contextSource.setPooled(false);
contextSource.afterPropertiesSet();
this.ldapTemplate = new LdapTemplate(contextSource);
this.ldapTemplate.setIgnorePartialResultException(true);
配置完成后,測試連接即可。
三、問題討論
需要注意的是,上述有一項配置非常重要,即
System.setProperty("com.sun.jndi.ldap.object.disableEndpointIdentification", "true");這項配置是JDK8之后需要加上的,官方在JDK8更新后加了端點校驗,即使是通過TrustManager繞過了證書校驗,有可能還是會因為證書不匹配報錯,當(dāng)然該項配置除了上述這種方式寫入,也可以通過JVM參數(shù)在程序啟動時加入
-Dcom.sun.jndi.ldap.object.disableEndpointIdentification=true
附該項校驗使用的源碼


以下是官方對該項配置的解釋:
Java 8 Update 181 (8u181)
發(fā)行版要點說明
IANA Data 2018e
- JDK 8u181 包含 IANA 時區(qū)數(shù)據(jù)版本 2018e。
- 有關(guān)詳細(xì)信息,請參閱 JRE 軟件中的時區(qū)數(shù)據(jù)版本。
**刪除的功能:**刪除 Java DB
- Java DB 也稱為 Apache Derby,已在本發(fā)行版中刪除。
- 建議您直接從以下網(wǎng)址的 Apache 項目獲取最新的 Apache Derby:
- https://db.apache.org/derby
- JDK-8197871(非公共)
**更改:**改進(jìn) LDAP 支持
- 已在 LDAPS 連接上啟用端點識別。
- 為提高 LDAPS(TLS 上的安全 LDAP)連接的強(qiáng)健性,默認(rèn)情況下已啟用端點識別算法。
- 請注意,可能在一些情況下,以前能夠成功連接到 LDAPS 服務(wù)器的一些應(yīng)用程序可能不再能夠成功連接。如果此類應(yīng)用程序認(rèn)為合適的話,它們可能會使用新系統(tǒng)屬性禁用端點識別:com.sun.jndi.ldap.object.disableEndpointIdentification。
- 定義此系統(tǒng)屬性(或者將它設(shè)置為 true)可禁用端點識別算法。
參考資料
- https://stackoverflow.com/questions/30546193/spring-ldapcontextsource-ignores-sslsocketfactory/30573130
- https://docs.spring.io/spring-ldap/docs/2.3.3.RELEASE/reference/
- https://java.com/zh-CN/download/help/release_changes.html
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot實現(xiàn)列表數(shù)據(jù)導(dǎo)出為Excel文件
這篇文章主要為大家詳細(xì)介紹了在Spring?Boot框架中如何將列表數(shù)據(jù)導(dǎo)出為Excel文件,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下2024-02-02
java拋出異常后,后續(xù)代碼是否繼續(xù)執(zhí)行詳解
這篇文章主要給大家介紹了關(guān)于java拋出異常后,后續(xù)代碼是否繼續(xù)執(zhí)行詳?shù)南嚓P(guān)資料,在Java編程中,異常是當(dāng)程序執(zhí)行時遇到問題時拋出的一種特殊情況,需要的朋友可以參考下2023-07-07
JSP頁面pageEncoding和contentType屬性
有關(guān)于JSP頁面中pageEncoding和contentType屬性。2013-04-04
SpringBoot自定義加載yml實現(xiàn)方式,附源碼解讀
這篇文章主要介紹了SpringBoot自定義加載yml實現(xiàn)方式附源碼解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
java數(shù)據(jù)庫批量插入數(shù)據(jù)的實現(xiàn)
本文主要介紹了java數(shù)據(jù)庫批量插入數(shù)據(jù)的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-05-05
NetBeans安裝提示neatbeans cannot find java 1.8 or higher
今天小編就為大家分享一篇關(guān)于NetBeans安裝提示neatbeans cannot find java 1.8 or higher,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-04-04
SpringBoot中SmartLifecycle的使用解析
這篇文章主要介紹了SpringBoot中SmartLifecycle的使用解析,SmartLifecycle是一個擴(kuò)展了Lifecycle接口,可以跟蹤spring容器ApplicationContext刷新或者關(guān)閉的接口,實現(xiàn)該接口的實現(xiàn)類有特定的執(zhí)行順序,需要的朋友可以參考下2023-11-11

