如何在LDAP中向SocketFactory发送参数

2022-07-20 00:00:00 ssl ldap java jsse jndi

下面示例代码的意思并不重要,我想问的是如何将传入的certFileName作为参数发送给socketFactory,因为我需要对不同的端点使用不同的certFileName,谢谢

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;
    }
}

谢谢!


解决方案

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

相关文章