Tuesday 19 July 2016

Android AD authentication, JNDI Sample to check user in Active Directory (AD)

If you are creating some mobile app to allow only for users who are listed in company Active Directory, then JNDI implementation can be the better approach for login. In this approach user should login with their AD credentials in mobile app. App will send request to AD to check whether user is listed in AD or not. 
This method is more secure and protective. The best advantage is, you don’t need to create separate table in backend database to track users. If you have to block user then just remove from AD. Below is the code sample with JNDI:
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class AuthenticationClass {

public static void main(String[] args) {

Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION"simple");
env.put(Context.PROVIDER_URL"ldap://AD_IP:port_no");
env.put(Context.SECURITY_PRINCIPAL"username");
env.put(Context.SECURITY_CREDENTIALS"password");
 
DirContext ctx;

try {
    // Authenticate the logon user
    ctx = new InitialDirContext(env);
 
    /**
     * Once the above line was executed successfully, the user is said to be authenticated and the InitialDirContext object will be created. IF user not found then it will throw exception.
     */
    System.out.print("Authenticated");
 
catch (NamingException ex) {
    // Authentication failed, just check on the exception and do something about it.
System.out.print("Authentication failed: "+ex.getMessage());
ex.printStackTrace();
}
}
}
This is very easy to implement and code size is also less.
Please feel free to comment for any clarification or suggestion.
***

No comments:

Post a Comment