This is a simple example through which we will connect to the LDAP Server and authenticate user.
I have used ApacheDS Server as a LDAP Server. Install ApacheDS server and run it.
Following is a servlet used. make login.html and use as it Login.java
I have used ApacheDS Server as a LDAP Server. Install ApacheDS server and run it.
Following is a servlet used. make login.html and use as it Login.java
package ajaxdemo.action; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.naming.*; import javax.naming.directory.*; import java.util.Hashtable; public class Login extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { public Login() { super(); } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String SUCCESS = "Success.html"; final String FAILURE = "Failure.html"; String strUrl = "login.html"; String username = request.getParameter("username"); String password = request.getParameter("password"); Hashtable env = new Hashtable(11); boolean b = false; env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:10389"); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "uid=" + username + ",ou=system"); env.put(Context.SECURITY_CREDENTIALS, password); try { // Create initial context DirContext ctx = new InitialDirContext(env); // Close the context when we're done b = true; ctx.close(); } catch (NamingException e) { b = false; } finally { if (b) { System.out.print("Success"); strUrl = SUCCESS; } else { System.out.print("Failure"); strUrl = FAILURE; } } RequestDispatcher rd = request.getRequestDispatcher(strUrl); rd.forward(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } }Enjoy LDAP!! :)
Can I have java code to reset ldap user password ?
ReplyDeleteHi I am getting NameNotFoundException while using LDAP against Active directory , any help ?
ReplyDeleteNice tutorial,by the way LDAP authentication is quite easy to implement for active directory or any other LDAP server if you use spring security. you can do this by just adding few configs and it lot more maintainable. See How to authenticate against LDAP active directory using Spring for step by step guide
ReplyDeleteThanks...
ReplyDeleteNice Post.
ReplyDelete