openLDAP win installation and deployment and java CRUD interface

Keywords: Java Windows

catalogue

summary
testing environment
setup script
Configuration startup
Client introduction
Configuration of ldif file for multi-level DC
java interface writing test

[1] . overview

What is LDAP? I won't talk about the concept here. There are many online searches. The focus of this paper is to introduce how to install and configure openLDAP software on windows platform.

openLDAP official website: http://www.openldap.org/

[2] Test environment

Windows 10 – 64 bit
openLDAP version: 2.4.49
Official website download address: https://www.maxcrc.de/download/
My download address: https://www.maxcrc.de/wp-content/uploads/2020/04/OpenLDAPforWindows_x86.zip

[3] . installation process

Follow the prompts until next is installed:







After installation, find the OpenLDAP Service in the system service, stop the service first, and then change the startup type to manual for your own test.

[4] . configuration startup

Installation directory: C:\OpenLDAP

Edit the file: C:\OpenLDAP\slapd.conf and find the following:
1 suffix"dc=maxcrc,dc=com"
2 rootdn "cn=Manager,dc=maxcrc,dc=com"

 suffix"dc=maxcrc,dc=com"
 rootdn "cn=Manager,dc=maxcrc,dc=com"

Change to

suffix"dc=micmiu,dc=com"
rootdn "cn=Manager,dc=micmiu,dc=com"

Open the console, switch to the openLDAP installation directory, and start openLDAP. The command is as follows:

slapd.exe -d 1 -f ./slapd.conf

You will see the following log information on the console:

Log information: slapd starting indicates that the service has been started.

Create a new file: C:\OpenLDAP\mydemo.ldif, as follows:

dn:dc=micmiu,dc=com
objectclass:domain
objectclass:top
o:Michael Blog
dc:micmiu
 
dn:ou=Developer,dc=micmiu,dc=com
objectclass:organizationalUnit
ou:Developer
description:Container fordeveloper entries
 
dn:ou=Tester,dc=micmiu,dc=com
objectclass:organizationalUnit
ou:Tester
description:Container fortest entries
 
dn:uid=Michael,ou=Developer,dc=micmiu,dc=com
uid:Michael
objectClass:inetOrgPerson
mail:sjsky_007@gmail.com
userPassword:111111
labeledURI:http://www.micmiu.com
sn:Sun
cn:Michael Sun
 
dn:uid=Miumiu,ou=Tester,dc=micmiu,dc=com
uid:Miumiu
objectClass:inetOrgPerson
userPassword:111111
labeledURI:http://www.micmiu.com
sn:Wu
cn:Miumiu Wu

tips: the format should be strict. There should be no spaces at the beginning and end of each line

Then switch to the openLDAP installation directory in the console and execute the ldapadd command:

slapadd -v -l mydemo.ldif -f slapd.conf

Parameter Description:

-x use simple authentication
-D specifies the administrator DN (consistent with that configured in slapd.conf)
-W capital w means enter the password according to the prompt after entering. You can use - w password in lowercase to enter the password directly
-f file name of LDIF data to be imported
-h IP address of the directory server
mydemo.ldif is the name of the file

After adding successfully, the following information will be displayed:

Verify the added information,

First in OpenLDAP of ClientTools In the file
cd C:\OpenLDAP\ClientTools
 In execution
ldapsearch-x-b"dc=micmiu,dc=com" "(objectclass=*)"

The query results are as follows:

Validation succeeded.

[5] I. client introduction

A client was found online: LdapBrowser282. The attachment provides relevant downloads: http://www.micmiu.com/wp-content/uploads/2012/05/LdapBrowser282.zip

After downloading and decompressing, double-click the lbe.bat file directly to run it.

Select localhost to enter

The relevant information added before can be queried correctly.

[6] Java calling interface

package com.doaron.controller;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import java.util.Hashtable;
import java.util.Vector;


public class TestOpenLDAP {
    DirContext dc = null;
    String account = "Manager";//The account that operates on LDAP. The default is Manager.
    String password = "secret";//Password for the account Manager.
    String root = "dc=micmiu,dc=com"; //DC of the root node of LDAP

  /*  public TestOpenLDAP() {
        //init();

        //Add node
        //add();

        //delete("ou=hi,dc=example,dc=com");//Delete the "ou=hi,dc=example,dc=com" node

        //modifyInformation("ou=hi,dc=example,dc=com");//Modify the "ou=hi,dc=example,dc=com" attribute


        searchInformation("dc=example,dc=com", "", "(objectclass=*)");//Traverse all root nodes

        //Rename the node "ou=new,o=neworganization,dc=example,dc=com"
        //renameEntry("ou=new,o=neworganization,dc=example,dc=com","ou=neworganizationalUnit,o=neworganization,dc=example,dc=com");

        //searchInformation("o=neworganization,dc=example,dc=com","","(objectclass=*)");//Traverse the sub nodes of the specified node
        close();
    }*/

    public  DirContext init() {
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://127.0.0.1:389/");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, "cn=" + account + "," + root);
        env.put(Context.SECURITY_CREDENTIALS, password);
        try {
            dc = new InitialDirContext(env);//Initialize context
            System.out.println("Authentication successful");//This can be changed to exception throwing.
        } catch (javax.naming.AuthenticationException e) {
            System.out.println("Authentication failed");
        } catch (Exception e) {
            System.out.println("Authentication error:" + e);
        }
        return null;
    }

    public void close() {
        if (dc != null) {
            try {
                dc.close();
            } catch (NamingException e) {
                System.out.println("NamingException in close():" + e);
            }
        }
    }

    public void add() {
        try {
            //Organizational unit, penultimate root node
            /*String newUserName = "hi1";
            BasicAttributes attrs = new BasicAttributes();
            BasicAttribute objclassSet = new BasicAttribute("objectClass");
            objclassSet.add("top");
            objclassSet.add("organizationalUnit");
            attrs.put(objclassSet);
            attrs.put("ou", newUserName);
            dc.createSubcontext("ou=" + newUserName + "," + root, attrs);*/


            //Organization personnel
            String newUserName = "hi2";
            BasicAttributes attrs = new BasicAttributes();
            BasicAttribute objclassSet = new BasicAttribute("objectClass");
            objclassSet.add("inetOrgPerson");
            attrs.put(objclassSet);
            attrs.put("ou", newUserName);
            attrs.put("uid","Tester1");
            attrs.put("sn","User name");
            attrs.put("cn","Account name ");
            attrs.put("mail","1575687@163.com");
            attrs.put("mobile","55758849");
            attrs.put("userPassword","234234");
            dc.createSubcontext("uid=hi2,ou=Demo,dc=app1,dc=micmiu,dc=com", attrs);


        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Exception in add():" + e);
        }
    }

    public void delete(String dn) {
        try {
            dc.destroySubcontext(dn);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Exception in delete():" + e);
        }
    }

    public boolean modifyInformation(String dn) {
        try {
            ModificationItem[] mods = new ModificationItem[1];

            /*Add attribute*/
//            Attribute attr0 = new BasicAttribute("sn",
//                    "Test");
//            mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE,attr0);

            /*modify attribute*/
            Attribute attr0 = new BasicAttribute("sn", "Test 1");
            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    attr0);

            /*Delete attribute*/
//            Attribute attr0 = new BasicAttribute("sn",
//                    "Tester1");
//            mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE,
//                    attr0);
            dc.modifyAttributes(dn, mods);
            return true;
        } catch (NamingException ne) {
            ne.printStackTrace();
            System.err.println("Error: " + ne.getMessage());
            return false;
        }

    }

    /**
     * @param base : Root node (in this case, "dc=example,dc=com")
     * @param scope : The search scope is divided into "base" (this node), "one" (single layer), "" (traversal)
     * @param filter : Specify child nodes (the format is "(objectclass = *)", * refers to all, or you can specify a specific type of tree node)
     */
    public void searchInformation(String base, String scope, String filter) {
        SearchControls sc = new SearchControls();
        if (scope.equals("base")) {
            sc.setSearchScope(SearchControls.OBJECT_SCOPE);
        } else if (scope.equals("one")) {
            sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        } else {
            sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
        }

        NamingEnumeration ne = null;
        try {
            ne = dc.search(base, filter, sc);
            // Use the NamingEnumeration object to cycle through
            // the result set.
            while (ne.hasMore()) {
                System.out.println();
                SearchResult sr = (SearchResult) ne.next();
                String name = sr.getName();
                if (base != null && !base.equals("")) {
                    System.out.println("entry: " + name + "," + base);
                } else {
                    System.out.println("entry: " + name);
                }

                Attributes at = sr.getAttributes();
                NamingEnumeration ane = at.getAll();

                while (ane.hasMore()) {
                    Attribute attr = (Attribute) ane.next();
                    String attrType = attr.getID();
                    NamingEnumeration values = attr.getAll();
                    Vector vals = new Vector();
                    // Another NamingEnumeration object, this time
                    // to iterate through attribute values.
                    while (values.hasMore()) {
                        Object oneVal = values.nextElement();
                        if (oneVal instanceof String) {
                            System.out.println(attrType + ": " + (String) oneVal);
                        } else {
                            System.out.println(attrType + ": " + new String((byte[]) oneVal));
                        }
                    }
                }
            }
        } catch (Exception nex) {
            System.err.println("Error: " + nex.getMessage());
            nex.printStackTrace();
        }
    }

    public boolean renameEntry(String oldDN, String newDN) {
        try {
            dc.rename(oldDN, newDN);
            return true;
        } catch (NamingException ne) {
            System.err.println("Error: " + ne.getMessage());
            return false;
        }
    }

    public static void main(String[] args) {
        TestOpenLDAP testOpenLDAP=new TestOpenLDAP();
        //authentication
        DirContext ctx = testOpenLDAP.init();

        //Traverse all root nodes
        testOpenLDAP.searchInformation("uid=hi2,ou=Demo,dc=app1,dc=micmiu,dc=com","","(objectclass=*)");


        //add to
        //testOpenLDAP.add();


        //Modify the attribute "ou=hi1,dc=micmiu,dc=com"
         //testOpenLDAP.modifyInformation("uid=hi2,ou=Demo,dc=app1,dc=micmiu,dc=com");

        //Delete the "ou=hi1,dc=micmiu,dc=com" node
        // testOpenLDAP.delete("ou=hi1,"+ testOpenLDAP.root);



        //close
        testOpenLDAP.close();
    }
}

Posted by phpnoobie on Fri, 19 Nov 2021 07:49:31 -0800