java – 如何接受JNDI / LDAP连接的自签名证书?

前端之家收集整理的这篇文章主要介绍了java – 如何接受JNDI / LDAP连接的自签名证书?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要通过SSL连接到LDAP目录.

在非生产环境中,我们使用自签名证书,当然无法验证:

javax.naming.CommunicationException: simple bind Failed: ldapserver:636 [Root exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building Failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target]
 at com.sun.jndi.ldap.LdapClient.authenticate(LdapClient.java:197)
 at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2694)
 at com.sun.jndi.ldap.LdapCtx.<init>(LdapCtx.java:293)
 at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(LdapCtxFactory.java:175)
 at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(LdapCtxFactory.java:193)
 at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(LdapCtxFactory.java:136)
 at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:66)
 at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
 at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
 at javax.naming.InitialContext.init(InitialContext.java:223)
 at javax.naming.ldap.InitialLdapContext.<init>(InitialLdapContext.java:134)

我知道如何使用一个custom trust manager for SSL-enabled connections,但不知道如何使用一个与JNDI API连接,我不管理实际的连接.也就是说,以下标准设置将在哪里可以插入信任管理器?

提前致谢.

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL,"ldaps://ldapserver:636");
env.put(Context.SECURITY_PROTOCOL,"ssl");
env.put(Context.SECURITY_AUTHENTICATION,"simple");
env.put(Context.SECURITY_PRINCIPAL,"myUser");
env.put(Context.SECURITY_CREDENTIALS,"myPassword");
LdapContext ctx = new InitialLdapContext(env,null);
ctx.search (...)

解决方法

根据JNDI文档,似乎可以设置一个定制的SSLSocketFactory

http://download.oracle.com/javase/1.5.0/docs/guide/jndi/jndi-ldap-gl.html#socket

public class MySSLSocketFactory extends SocketFactory {
    private SSLSocketFactory sf;

    public MySSLSocketFactory() {
        KeyStore keyStore = ... /* Get a keystore containing the self-signed certificate) */
        TrustManagerFactory tmf = TrustManagerFactory.getInstance();
        tmf.init(keyStore);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null,tmf.getTrustManagers(),null);
        sf = ctx.getSocketFactory();
    }

    /* delegate SSLSocketFactory public methods to sf */
    ...
}

配置环境以使用此套接字工厂

env.put("java.naming.ldap.factory.socket","com.example.MySSLSocketFactory");
原文链接:https://www.f2er.com/java/122478.html

猜你在找的Java相关文章