Showing posts with label LDAP. Show all posts
Showing posts with label LDAP. Show all posts

Monday 23 April 2018

Java code to read objectSID from LDAP (Active Directory)

//Java code to read objectSID from LDAP (Active Directory)

import java.io.IOException;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class LDAPSID {

public static String getObjectSID(String objectName) {
Hashtable env = new Hashtable(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
    //Domain
String dirRoot = "DC=ABCD,DC=CORP";
    //LDAP User Name
String adminName = "CN=Rakesh,OU=XXX,OU=XXX,OU=XXX,DC=XXX";
    //LDAP Password
String adminPassword ="password";
    //Ldap URL
String ldapURL ="ldap://localhost:389";
    env.put(Context.SECURITY_AUTHENTICATION,"simple");
    env.put(Context.SECURITY_PRINCIPAL,adminName);
    env.put(Context.SECURITY_CREDENTIALS,adminPassword);
    env.put("com.sun.jndi.ldap.connect.pool", "true");
    env.put("java.naming.ldap.attributes.binary","objectSID");

    try {
        env.put(Context.PROVIDER_URL, ldapURL);
        env.put("com.sun.jndi.ldap.netscape.schemaBugs", "true");
        DirContext ctx = new InitialDirContext(env);
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
       String searchFilter = "(&(objectClass=user)(cn=" + objectName +"))";
        String searchBase ="DC=ABCD,DC=CORP";
        int totalResults = 0;
        String returnedAtts[]={"cn","distinguishedName","objectSID"};
        searchControls.setReturningAttributes(returnedAtts);
        NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchControls);
        while (answer.hasMoreElements()) {
            SearchResult sr = (SearchResult)answer.next();
            Attributes attrs = sr.getAttributes();
            if (attrs != null) {                         
                try {
                    for (NamingEnumeration ae = attrs.getAll();ae.hasMore();) {
                        Attribute attr = (Attribute)ae.next();
                        System.out.println("CN :" +attrs.get("cn").get());
                        byte[] SID = (byte[])attrs.get("objectSID").get();
                        String strSID = getSIDasStringOfBytes(SID);
                        System.out.println("Object SID :" + strSID );
                        return strSID;
                    }

                }     
                catch (NamingException e)    {
                    System.err.println("Problem listing membership: " + e);
                    return "ERROR";
                }
                ctx.close();
            }
        }
                      
        } catch (NamingException ne) {
        ne.printStackTrace();
        System.out.println("Error: " + ne);
        return "ERROR";
        }
        return "ERROR";
}

public static String getSIDasStringOfBytes(byte[] sid) {
    String strSID = "";
    int version;
    long authority;
    int count;
    String rid = "";
    strSID = "S";

     // get version
    version = sid[0];
    strSID = strSID + "-" + Integer.toString(version);
    for (int i=6; i>0; i--) {
        rid += byte2hex(sid[i]);
    }

    // get authority
    authority = Long.parseLong(rid);
    strSID = strSID + "-" + Long.toString(authority);

    //next byte is the count of sub-authorities
    count = sid[7]&0xFF;

    //iterate all the sub-auths
    for (int i=0;i<count;i++) {
        rid = "";
        for (int j=11; j>7; j--) {
            rid += byte2hex(sid[j+(i*4)]);
        }
        strSID = strSID + "-" + Long.parseLong(rid,16);
    }
    return strSID;    
}

public static String byte2hex(byte b) {
String ret = Integer.toHexString((int)b&0xFF);
if (ret.length()<2) ret = "0"+ret;
return ret;
}

public static void main(String[] args) throws IOException {
//Search Filter is "CN"
getObjectSID("Rakesh K");
System.out.println("It's Done");
}

}

Tuesday 8 November 2016

Java code to get user details from LDAP

//Java code to get user details from LDAP

import java.util.Hashtable;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class GetUserDetailsFromLDAP {
static String ldapSearchBase = "DC=Company,DC=internal";
private static DirContext ctx = null;
private static DirContext getActiveDirectoryContext() throws Exception {

final Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
properties.put(Context.PROVIDER_URL,"ldap://localhost:389");
properties.put(Context.SECURITY_AUTHENTICATION,"simple");
properties.put(Context.SECURITY_PRINCIPAL, "CN=userName");
properties.put(Context.SECURITY_CREDENTIALS,"Password");
return new InitialDirContext(properties);

}
public String[] getUser(String userID) throws Exception {

String DisplayName="";
String location="";
String attValue = "";
DirContext directoryContext  = getActiveDirectoryContext();
String returnedAttrs[] = {"displayName","userPrincipalName", "cn", "mail","sn","company","department","memberof"};
String returnedAttrsValues[]=new String[2];
SearchControls searchCtls = new SearchControls();

//Search Scope - 
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);//(or)SearchControls.ONELEVEL_SCOPE (or) SearchControls.OBJECT_SCOPE

searchCtls.setReturningAttributes(returnedAttrs);
String searchFilter = userID;
NamingEnumeration users = directoryContext.search(ldapSearchBase, searchFilter, searchCtls);
if(!users.hasMoreElements())
{
returnedAttrsValues[0]=userID;
}
else{
while (users.hasMoreElements())
{
SearchResult sr = (SearchResult)users.next();
Attributes attrs = sr.getAttributes();
if (attrs.size() == 0){
System.out.println("dddd");
}
else{
try {
for (NamingEnumeration ae = attrs.getAll();ae.hasMore();){
Attribute attr = (Attribute)ae.next();
System.out.println("Attribute = "+attr.toString());
String id = attr.getID();
NamingEnumeration e = attr.getAll();
if(!e.hasMore())
{
returnedAttrsValues[0]=userID;
}
else{
while(e.hasMore()){
attValue = (String)e.next();
if(id.equalsIgnoreCase("DisplayName")){
DisplayName = attValue;
if(DisplayName!=null && !DisplayName.equals("")){
returnedAttrsValues[0]=attValue;
}
else{
returnedAttrsValues[0]=userID;

}
}
else if(id.equalsIgnoreCase("physicalDeliveryOfficeName")){
location = attValue;
returnedAttrsValues[1]=attValue;
}

}
}

}
}
catch (NamingException e){
System.out.println("[LDAP] Exception while retreiving Attr from LDAP"+e.getMessage());
System.out.println("[LDAP] Exception while retreiving Attr from LDAP"+e.getRootCause());

}

}
}
}
return returnedAttrsValues;
}

public static void main(String args[]) throws Exception{
GetUserDetailsFromLDAP gug = new GetUserDetailsFromLDAP();
gug.getUser("cn=userid"); //(or) mail= abc@gmail.com (or) sn=name (or) uid=name...etc 
}
}

Java code to get all users in LDAP Group

//Java code to get all users in LDAP Group

import java.util.Hashtable;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class GetUsersFrormLDAPGroup {
static String ldapSearchBase = "DC=Company,DC=internal";
private static DirContext ctx = null;
private static DirContext getActiveDirectoryContext() throws Exception {

final Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
properties.put(Context.PROVIDER_URL,"ldap://localhost:389");
properties.put(Context.SECURITY_AUTHENTICATION,"simple");
properties.put(Context.SECURITY_PRINCIPAL, "CN=UserName");
properties.put(Context.SECURITY_CREDENTIALS,"Password");
return new InitialDirContext(properties);

}
public void getGroupUsers(String searchBase, String searchFilter, String returnedAttrs[], int maxResults)
{
Hashtable userEntries = null;
String member="";
try{
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);      
searchCtls.setReturningAttributes(returnedAttrs);
ctx=getActiveDirectoryContext();
try{
System.out.println("Search Base: "+searchBase);
System.out.println("Search Filter: "+searchFilter);
NamingEnumeration users = ctx.search(searchBase, searchFilter, searchCtls);
if(users.hasMoreElements() == false){
System.out.println("Not find any object with this filter " + searchFilter + " and searchBase " + searchBase);
}

int k = 0;
String attValue = "";
userEntries = new Hashtable();
while (users.hasMoreElements()){
if(k >= maxResults)
break;        
SearchResult sr = (SearchResult)users.next();
Attributes attrs = sr.getAttributes();
if (attrs.size() == 0){
System.out.println("Could not find attribute " + returnedAttrs[0] + " for this object.");
}else{

try{          
for (NamingEnumeration ae = attrs.getAll();ae.hasMore();){ 
Attribute attr = (Attribute)ae.next();                
String id = attr.getID();
for (NamingEnumeration e = attr.getAll();e.hasMore();){                
attValue = (String)e.next();
if(id.equalsIgnoreCase("member"))
member = attValue;
System.out.println("member :"+member);
else
{
System.out.println("empty");
}
}
}
}catch(NamingException e){
System.out.println("Problem listing membership:"+e);          
}
}
k++;
}
}catch (NamingException e){
System.out.println("Problem searching directory: "+e);          
}     
ctx.close();
ctx=null;  
}catch (Exception namEx){
System.out.println("Exception while fetching the users from LDAP::"+namEx);      
}    

}
public static void main(String args[]) throws Exception{
GetUsersFrormLDAPGroup gug = new GetUsersFrormLDAPGroup();
String returnedAttrs[] = {"cn","member", "name"};
String searchFilter="CN=GroupName";
gug.getGroupUsers(ldapSearchBase,searchFilter, returnedAttrs, Integer.parseInt("2000"));
}
}

Friday 11 December 2015

Java code to Create/Delete user in LDAP

//Java code to Create/Delete user in LDAP

// Establish a LDAP connection

public static LdapContext getInitialLdapContext()
        throws Exception
    {
        LdapContext ctx = null;
        String dnusername = "cn=root,ou=users, o=sample,c=country"; //Admin user name
        String dnpwd = "abcd@123"; //Admin Password
        try
        {
            Control rctls[] = {new PasswordPolicyControl(true)};
            String ldapHostName = bundle.getString("LDAP_IP");
            String ldapHostRMIPort = bundle.getString("LDAP_PORT");
            String providerURL = (new StringBuilder("ldap://")).append(ldapHostName).append(":").append(ldapHostRMIPort).toString();
            System.out.println("URL  =  "+ providerURL);
            Hashtable env = new Hashtable();
            env.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
            env.put("java.naming.provider.url", providerURL);
            env.put("java.naming.security.authentication", "simple");
            env.put("java.naming.security.principal", dnusername);
            env.put("java.naming.security.credentials", dnpwd);
            ctx = new InitialLdapContext(env, rctls);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return ctx;
    }
    private static String getUserDN(String username)
    {
        return (new StringBuilder("cn=")).append(username).append(",").append("ou=users, o=sample,c=country").toString();
    }
   
   
    //Create a user
   private static void addUser(String username, String surname,  String titleprop, String mailprop, String employeenumberprop, String mobileprop, String displayNameprop, String password)
       // throws NamingException
    {
        private static DirContext context;
        context = getInitialLdapContext();
        Attributes container = new BasicAttributes();
        Attribute objClasses = new BasicAttribute("objectClass");
        objClasses.add("organizationalPerson");
        objClasses.add("inetOrgPerson");
        objClasses.add("person");
        objClasses.add("top");
        Attribute cn = new BasicAttribute("cn", username);
        Attribute sn = new BasicAttribute("sn", surname);
        Attribute uid = new BasicAttribute("uid", username);
        Attribute title = new BasicAttribute("title", titleprop);
        Attribute mail = new BasicAttribute("mail", mailprop);
        Attribute mobile = new BasicAttribute("mobile", mobileprop);
        Attribute employeeNumber = new BasicAttribute("employeeNumber", employeenumberprop);
        Attribute userPassword = new BasicAttribute("userpassword", password);
        Attribute  displayName = new BasicAttribute("displayName",displayNameprop);
        container.put(objClasses);
        container.put(sn);
        container.put(uid);
        container.put(title);
        container.put(mail);
        container.put(mobile);
        container.put(employeeNumber);
        container.put(countryCode);
        container.put(displayName);

        container.put(userPassword);
       try{
        context.createSubcontext(getUserDN(username), container);
       }
       catch (Exception e) {
        // TODO: handle exception
           log.info(e);
    }
       
       System.out.println((new StringBuilder(String.valueOf(password))).append("- is the Password for user- ").append(username).toString());
       
    }
   
    //Delete a user
    private static void deleteUser(String username)
        throws NamingException
    {
        try
        {
            context.destroySubcontext(getUserDN(username));
            System.out.println((new StringBuilder("User has been deleted successfully - ")).append(username).toString());
        }
        catch(NameNotFoundException namenotfoundexception) {
            log.info(namenotfoundexception);
        }
    }