Search This Blog

Wednesday, April 30, 2014

LDAP - ADS User Creation

Here is the example to create LDAP - ADS User Creation.

Files:-
Create a main folder and paste this two properties file.
Create a sub folders like com/vijay/ldap and paste the java content in Ldap.java.

Ldap.properties
         To make connection with your Ldap/ADS.
Ldap-user-settings.properties
         To make settings for your new user.
 Ldap.java
          It is a java program which can connect ldap and create user based on your distinguish Name.


ldap.properties

#* @author drvijay
#* @date 29-04-2014 4PM

ldap.initial.context.factory=com.sun.jndi.ldap.LdapCtxFactory
ldap.security.authentication=simple

ldap.domain.name=domain.com
ldap.domain.root=DC=sdex,DC=com
ldap.admin.name=CN=Administrator,CN=Users,DC=domain,DC=com
ldap.organisationUnit=ou=subOrg,ou=parentOrg
ldap.admin.pass=test123
ldap.domain.url=ldap://127.0.0.1:389



#ldap.organisationUnit=ou=subOrg,ou=parentOrg  you can change the ou= based on your ldap structure


ldap-user-settings.properties

#* @author drvijay
#* @date 29-04-2014 4PM

#loop configuration
ldap.concatenate.start.value=1
ldap.concatenate.end.value=1

#loop attributes
ldap.userName=userName{0}
ldap.firstName=Vijay{0}
ldap.displayName={0} D R

#repeated attributes
ldap.lastName=P
ldap.userPassword=test123
ldap.mobile=9842088860
ldap.company=infovijay
ldap.mail=drvijayy2k2@gmail.com
ldap.postalCode=636702
ldap.st=TN
ldap.city=DPI
ldap.country=IN


Ldap.Java

package com.vijay.ldap;

import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

/**
 *
 * @author drvijay
 * @date 29-04-2014 4PM
 */

public class Ldap
{

    private static ResourceBundle                ldapSystemProperties        = ResourceBundle.getBundle ( "ldap" );
    private static ResourceBundle                ldapUserSettingsProperties    = ResourceBundle.getBundle ( "ldap-user-settings" );

    private static String                        DOMAIN_NAME                    = ldapSystemProperties.getString ( "ldap.domain.name" );
    private static String                        DOMAIN_ROOT                    = ldapSystemProperties.getString ( "ldap.domain.root" );
    private static String                        ADMIN_NAME                    = ldapSystemProperties.getString ( "ldap.admin.name" );
    private static String                        ADMIN_PASS                    = ldapSystemProperties.getString ( "ldap.admin.pass" );
    private static String                        DOMAIN_URL                    = ldapSystemProperties.getString ( "ldap.domain.url" );
    private static String                        INITIAL_CONTEXT_FACTORY        = ldapSystemProperties.getString ( "ldap.initial.context.factory" );
    private static String                        SECURITY_AUTHENTICATION        = ldapSystemProperties.getString ( "ldap.security.authentication" );
    private static String                        _organisationUnit            = ldapSystemProperties.getString ( "ldap.organisationUnit" );

    // some useful constants from lmaccess.h
    private static int                            UF_ACCOUNTDISABLE            = 0x0002;
    private static int                            UF_PASSWD_NOTREQD            = 0x0020;
    private static int                            UF_PASSWD_CANT_CHANGE        = 0x0040;
    private static int                            UF_NORMAL_ACCOUNT            = 0x0200;
    private static int                            UF_DONT_EXPIRE_PASSWD        = 0x10000;
    private static int                            UF_PASSWORD_EXPIRED            = 0x800000;

    private static String                        _userName                    = ldapUserSettingsProperties.getString ( "ldap.userName" );
    private static String                        _firstName                    = ldapUserSettingsProperties.getString ( "ldap.firstName" );
    private static String                        _lastName                    = ldapUserSettingsProperties.getString ( "ldap.lastName" );
    private static String                        _userPassword                = ldapUserSettingsProperties.getString ( "ldap.userPassword" );
    private static String                        _mobile                        = ldapUserSettingsProperties.getString ( "ldap.mobile" );
    private static String                        _company                    = ldapUserSettingsProperties.getString ( "ldap.company" );
    private static String                        _displayName                = ldapUserSettingsProperties.getString ( "ldap.displayName" );
    private static String                        _mail                        = ldapUserSettingsProperties.getString ( "ldap.mail" );
    private static String                        _postalCode                    = ldapUserSettingsProperties.getString ( "ldap.postalCode" );
    private static String                        _st                            = ldapUserSettingsProperties.getString ( "ldap.st" );
    private static String                        _city                        = ldapUserSettingsProperties.getString ( "ldap.city" );
    private static String                        _country                    = ldapUserSettingsProperties.getString ( "ldap.country" );

    private static String                        cnValue;

    private static int                            loopStart                    = Integer.parseInt ( ldapUserSettingsProperties.getString ( "ldap.concatenate.start.value" ) );
    private static int                            loopEnd                        = Integer.parseInt ( ldapUserSettingsProperties.getString ( "ldap.concatenate.end.value" ) );

    private static LdapContext                    context;
    private static Hashtable     env                            = new Hashtable ();

    /**
     * Instantiates a new ldap.
     */
    public Ldap ()
    {
    }

    /**
     * Instantiates a new ldap.
     *
     * @param userName
     *            the user name
     * @param firstName
     *            the first name
     * @param lastName
     *            the last name
     * @param organisationUnit
     *            the organisation unit
     */
    public Ldap ( String userName, String firstName, String lastName, String organisationUnit )
    {
        this._userName = userName;
        this._firstName = firstName;
        this._lastName = lastName;
        this._organisationUnit = organisationUnit;
    }

    /**
     * The main method.
     *
     * @param args
     *            the arguments
     */
    public static void main ( String [] args )
    {
        // Ldap user = new Ldap ( userName, firstName, lastName, organisationUnit );
        Ldap user = new Ldap ();

        try
        {
            env.put ( Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY );
            env.put ( Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION );
            env.put ( Context.SECURITY_PRINCIPAL, ADMIN_NAME );
            env.put ( Context.SECURITY_CREDENTIALS, ADMIN_PASS );
            env.put ( Context.PROVIDER_URL, DOMAIN_URL );
            context = new InitialLdapContext ( env, null );

            for ( int i = loopStart; i <= loopEnd; i++ )
            {
                try
                {
                    // replace dynamic parameters from properties
                    _userName = MessageFormat.format ( ldapUserSettingsProperties.getString ( "ldap.userName" ), i );
                    _firstName = MessageFormat.format ( ldapUserSettingsProperties.getString ( "ldap.firstName" ), i );
                    _displayName = MessageFormat.format ( ldapUserSettingsProperties.getString ( "ldap.displayName" ), _firstName );

                    // create user
                    System.out.println ( "User : " + _userName + " created Status : " + user.addUser () );

                    // DirContext sslCtx = new InitialDirContext ( env );
                    // changePassword ( sslCtx, getUserDN ( cnValue, user.organisationUnit ), "test123" );
                }
                catch ( Exception e )
                {
                    System.err.println ( e.getMessage () );
                    e.printStackTrace ();
                }
            }

        }
        catch ( NamingException e )
        {
            System.err.println ( "Problem creating object: " + e );
            e.printStackTrace ();
        }
        catch ( Exception e )
        {
            System.err.println ( "Problem creating object: " + e );
            e.printStackTrace ();
        }
    }

    /**
     * Gets the user dn.
     *
     * @param aUsername
     *            the a username
     * @param aOU
     *            the a ou
     * @return the user dn
     */
    private static String getUserDN ( String aUsername, String aOU )
    {
        return "cn=" + aUsername + "," + aOU + "," + DOMAIN_ROOT;
    }

    /**
     * Adds the user.
     *
     * @return true, if successful
     * @throws NamingException
     *             the naming exception
     */
    public boolean addUser () throws NamingException
    {

        Attributes container = new BasicAttributes ();

        try
        {

            Attribute objClasses = new BasicAttribute ( "objectClass" );
            objClasses.add ( "top" );
            objClasses.add ( "person" );
            objClasses.add ( "organizationalPerson" );
            objClasses.add ( "user" );
            container.put ( objClasses );

            cnValue = new StringBuffer ( _firstName ).append ( " " ).append ( _lastName ).toString ();

            Attribute cn = new BasicAttribute ( "cn", cnValue );
            Attribute sAMAccountName = new BasicAttribute ( "sAMAccountName", _userName );
            Attribute principalName = new BasicAttribute ( "userPrincipalName", _userName + "@" + DOMAIN_NAME );

            Attribute givenName = new BasicAttribute ( "givenName", _firstName );
            Attribute sn = new BasicAttribute ( "sn", _lastName );
            Attribute uid = new BasicAttribute ( "uid", _userName );

            Attribute userPassword = new BasicAttribute ( "userpassword", _userPassword );
            Attribute mobile = new BasicAttribute ( "mobile", _mobile );
            Attribute company = new BasicAttribute ( "company", _company );
            Attribute displayName = new BasicAttribute ( "displayName", _displayName );
            Attribute mail = new BasicAttribute ( "mail", _mail );
            Attribute postalCode = new BasicAttribute ( "postalCode", _postalCode );
            Attribute st = new BasicAttribute ( "st", _st );
            Attribute l = new BasicAttribute ( "l", _city );
            Attribute c = new BasicAttribute ( "c", _country );
            Attribute userAccountControl = new BasicAttribute ( "userAccountControl", Integer.toString ( UF_NORMAL_ACCOUNT + UF_PASSWD_NOTREQD + UF_PASSWORD_EXPIRED + UF_DONT_EXPIRE_PASSWD ) );

            container.put ( sAMAccountName );
            container.put ( principalName );
            container.put ( cn );
            container.put ( sn );
            container.put ( givenName );
            container.put ( uid );
            container.put ( c );
            container.put ( l );
            container.put ( st );
            container.put ( postalCode );
            container.put ( mail );
            container.put ( displayName );
            container.put ( company );
            container.put ( mobile );
            container.put ( userAccountControl );
            container.put ( userPassword );

            context.createSubcontext ( getUserDN ( cnValue, _organisationUnit ), container );
            return true;
        }
        catch ( Exception e )
        {
            e.printStackTrace ();
            return false;
        }
    }

    /**
     * Gets the time.
     *
     * @param pwdLastSet
     *            the pwd last set
     * @return the time
     */
    private static Calendar getTime ( long pwdLastSet )
    {
        long javaTime = pwdLastSet - 0x19db1ded53e8000L;
        javaTime /= 10000;

        Calendar cal = Calendar.getInstance ();
        cal.setTimeInMillis ( javaTime );
        return cal;
    }

    /**
     * Encode password.
     *
     * @param pass
     *            the pass
     * @return the byte[]
     * @throws UnsupportedEncodingException
     *             the unsupported encoding exception
     */
    private static byte [] encodePassword ( String pass ) throws UnsupportedEncodingException
    {
        String ATT_ENCODING = "UTF-16LE";
        String pwd = "\"" + pass + "\"";
        byte bytes[] = pwd.getBytes ( ATT_ENCODING );

        return bytes;
    }

    /**
     * Change password.
     *
     * @param ctx
     *            the ctx
     * @param argRDN
     *            the arg rdn
     * @param argNewPassword
     *            the arg new password
     * @throws NamingException
     *             the naming exception
     */
    public static void changePassword ( DirContext ctx, String argRDN, String argNewPassword ) throws NamingException
    {

        ModificationItem [] modificationItem = new ModificationItem[1];
        try
        {
            modificationItem[0] = new ModificationItem ( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute ( "unicodePwd", encodePassword ( argNewPassword ) ) );
            ctx.modifyAttributes ( argRDN, modificationItem );
        }
        catch ( UnsupportedEncodingException e1 )
        {
            throw new RuntimeException ( e1.toString () );
        }
        catch ( NamingException e1 )
        {
            throw e1;
        }
    }

}








No comments:

Hit Counter


View My Stats