如何将参数发送到Ldap中的SocketFactory

时间:2012-03-26 01:41:41

标签: java ssl ldap jndi jsse

以下示例代码的含义并不重要,我想问的是如何将“certFileName”作为params发送到socketFactory,因为我需要使用不同的certFile到不同的endPoint,谢谢

public class LdapConnection
{

    private String host = "1.2.3.4"; //the correct ip...
    private String baseDn = "dc=x,dc=y,dc=com"; //the correct base DN

    private String username = "myUsername";
    private String password = "myPassword";

    private String connectionUrl = null;

    public void connectLdaps() throws Exception
    {
        connectionUrl = "ldaps://" + host + "/" + baseDn;

        System.out.println("Trying to connect to " + connectionUrl + " using LDAPS protocol");

        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put("java.naming.ldap.derefAliases", "finding");
        env.put(Context.PROVIDER_URL, connectionUrl);
        env.put(Context.SECURITY_AUTHENTICATION, "Simple");
        env.put(Context.SECURITY_PRINCIPAL, username);
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put("java.naming.ldap.factory.socket", MySocketFactory.class.getName());

        new InitialLdapContext(env, null);

        System.out.println("Connected successfully!");
    }

    public static void main(String[] args) throws Exception
    {
        LdapConnection ldapConnection = new LdapConnection();
        ldapConnection.connectLdaps();
    }

}

public class MySocketFactory extends SocketFactory
{
    private static MySocketFactory instance = null;
    private SSLContext sslContext = null;

    //I want to send this var from outside
    **private static String certFileName = "C:\\certs\\cert_by_hostname.cer";**

    public static SocketFactory getDefault()
    {
        if (instance == null)
        {
            try
            {
                instance = new MySocketFactory();
                instance.initFactory();
            }
            catch (Exception e)
            {
                e.printStackTrace();
                System.out.println("Returning null socket factory");
            }
        }

        return instance;
    }
}

可能是这样的:我应该在“外部”代码中做什么

public class MySocketFactory extends SocketFactory
{
    private MySocketFactory instance = null;
    private SSLContext sslContext = null;

    //I want to send this var from outside
    private String certFileName = null

    public MySocketFactory(String varCert)
    {
       certFileName = varCert;
    }
}

谢谢!

1 个答案:

答案 0 :(得分:1)

您根本不需要编写套接字工厂。请参阅JSSE参考指南。只需设置适当的系统属性即可。