微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/java/122478.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐