Image of LDAP authentication in Java

ADVERTISEMENT

Table of Contents

Introduction

In this tutorial, we share the common code block that is used to connect to an LDAP server in Java.

1. InitialDirContext

To connect to an LDAP server, you can use the InitialDirContext class provided by the JDK.

You can use the following block anytime you need to connect to an LDAP server:

private void connectToLDAP()
{
    try 
    {
        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, "ldap://ldap.forumsys.com:389");
        props.put(Context.SECURITY_PRINCIPAL, "uid=riemann,dc=example,dc=com");
        props.put(Context.SECURITY_CREDENTIALS, "password");
 
        InitialDirContext context = new InitialDirContext(props);
        System.out.println("Succesfully connected to LDAP server");
    } 
    catch (Exception e) 
    {
        System.out.println("Couldn't connect to LDAP server");
        e.printStackTrace();
    }
}

Summary

In this tutorial, we share the common code block that is used to connect to an LDAP server in Java.

Next Steps

If you're interested in learning more about the basics of Java, coding, and software development, check out our Coding Essentials Guidebook for Developers, where we cover the essential languages, concepts, and tools that you'll need to become a professional developer.

Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, feel free to reach out to jacob@initialcommit.io.

Final Notes