Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com

Wednesday, April 19, 2017

Authorize an user using LDAP authentication in Java.

LDAP authentication is now-a-days very useful for enterprises application. LDAP also acts as source of SSO [Single sign on]. Ldap stands for Lightweight Directory Access Protocol , in this post we are basically trying to authenticate an user using his windows credentials with Java. 





Prerequisite :

1. Java version 1.7 or higher

2. Springs 

3. You need to know your organizations LDAP url ,port number , username and password of manager account or service account.


Spring provides LDAP template which we can use for easy querying of LDAP server.


Below is the example code of LDAP authentication:




package dht.test.ldap.unittest;

import org.springframework.ldap.core.DistinguishedName;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.ldap.filter.AndFilter;
import org.springframework.ldap.filter.EqualsFilter;


public class LdapTest {

 public static void main(String[] args) throws Exception {

  LdapContextSource contextSource = new LdapContextSource();
  contextSource.setUrl("ldaps://Your-ldap-url-COM:portnum");
  contextSource.setBase("OU=org,DC=corp,DC=die,DC=com");
  contextSource.setUserDn("autoaccount01");
  contextSource.setPassword("We1c0me2ldap");
  contextSource.afterPropertiesSet();

  LdapTemplate ldapTemplate = new LdapTemplate(contextSource);
  ldapTemplate.afterPropertiesSet();

  boolean b = new LdapTest().authenticate(ldapTemplate, "dht3", "Dht@123");
  System.out.println("Authentication " + b);

 }

 public boolean authenticate(LdapTemplate ldapTemplate, String userName, String password) {
  AndFilter filter = new AndFilter();
  filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("sAMAccountName", userName));
  return ldapTemplate.authenticate(DistinguishedName.EMPTY_PATH, filter.toString(), password);

 }

}



 Above program returns Authentication successful if user has provided valid login credentials, false otherwise. 



Happy coding. Let us know if you get stuck somewhere.













No comments: