Implement LDAP authentication in Tomcat & JBoss server for Java app

In this article we will explore the ways to implementation of LDAP (Lightweight Directory Access Protocol) authentication in Tomcat as well as JBoss server. First let us see briefly what LDAP is.

Introduction to LDAP

Following is what Wikipedia has to say about LDAP: The Lightweight Directory Access Protocol, or LDAP is an application protocol for querying and modifying directory services running over TCP/IP. A directory is a set of objects with similar attributes organized in a logical and hierarchical manner. The most common example is the telephone directory, which consists of a series of names (either of persons or organizations) organized alphabetically, with each name having an address and phone number attached. An LDAP directory tree often reflects various political, geographic, and/or organizational boundaries, depending on the model chosen. LDAP deployments today tend to use Domain name system (DNS) names for structuring the topmost levels of the hierarchy. Deeper inside the directory might appear entries representing people, organizational units, printers, documents, groups of people or anything else that represents a given tree entry (or multiple entries).

Configurations in Tomcat Server

I assume you have installed JDK and Tomcat server and have set few environment variables such as CLASSPATH, PATH, JAVA_HOME, CATALINA_HOME etc. First step is to implement LDAP in Tomcat is to modify server.xml. Open server.xml from conf directory from your Tomcat installation directory and add following tag between tag <Host> and </Host>.
<Realm className="org.apache.catalina.realm.JNDIRealm" debug="99" connectionURL="ldap://ldap.viralpatel.net:389/" userPattern="{0}" />
Code language: HTML, XML (xml)
Also comment out the entry for <Realm>:
<!— <Realm className="org.apache.catalina.realm.UserDatabaseRealm" debug="0" resourceName="UserDatabase"/> -->
Code language: HTML, XML (xml)
Let us see now what are the different configuration parameters that we are using in above code.
  • className: This is the fully qualified Java class name of this Realm implementation. The value “org.apache.catalina.realm.JNDIRealm” must be specified here.
  • debug: This is the level of debugging detail logged by this Realm to the associated log file. Higher numbers generate more detailed output. If not specified, the default debugging detail level is zero (0).
  • connectionURL : This is a URL whose format is defined by the JNDI provider. It is usually an LDAP URL that specifies the domain name of the directory server to connect to, and optionally the port number and distinguished name (DN) of the required root naming context. Often the distinguished name of the user’s entry contains the username presented for authentication but is otherwise the same for all users. Here, the phrase “ldap://ldap.viralpatel.net:389/”, “ldap” represents a protocol; “ldap.viralpatel.net” represents a LDAP directory server to connect; “389” represents a valid port on the server.
  • userPattern : This is used to specify the DN, with “{0}” marking where the username should be substituted.
Next step will be to modify Web.xml and add security constraint information in it. Open the web.xml from WEB-INF directory of your J2EE project and add following code in it:
<security-constraint> <web-resource-collection> <web-resource-name>Logging Area</web-resource-name> <description> Authentication for registered users. </description> <url-pattern>/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>*</role-name> </auth-constraint> </security-constraint> <security-role> <role-name>*</role-name> </security-role> <login-config> <auth-method>BASIC</auth-method> <realm-name>Please enter your Username</realm-name> </login-config>
Code language: HTML, XML (xml)
Note that in above code we have mapped the URL /*. If we want to use authentication in some particular area of our website like some admin module than map particular URL with security-constraint.
<!—restricted files under folderAdmin” <url-pattern>/Admin/*</url-pattern> <!—restricted file OfficeDocIndex.jsp [/code] To fetch the user details in Java, copy following code in your JSP/Java file. [code="java"] import java.security.Principal; …… Principal principal = request.getUserPrincipal(); String userName = principal.getName(); .… [/code] Now once you start the Tomcat and visit your website, following popup will be shown. <img src="//www.viralpatel.net/app/uploads/2008/12/ldap-authentication-popup-tomcat-server.jpg" alt="ldap-authentication-popup-tomcat-server" title="ldap-authentication-popup-tomcat-server" width="326" height="289" class="alignnone size-full wp-image-394" /> <h2>Configurations in JBoss Server</h2> I assume you have installed JDK and JBoss server and have set few environment variables such as CLASSPATH, PATH, JAVA_HOME etc. First step is to implement LDAP in JBoss is to modify <strong>login-config.xml</strong>. Open login-config.xml from <strong>conf </strong>directory from your JBoss installation directory and add following tag. <!-- wp:code {"language": "xml"} --><pre class="wp-block-code"><code></code></pre><!-- /wp:code --> <application-policy name="website-domain"> <authentication> <login-module code="org.jboss.security.auth.spi.LdapLoginModule" flag="required"> <module-option name = "debug">true</module-option> <module-option name = "java.naming.factory.initial"> com.sun.jndi.ldap.LdapCtxFactory </module-option> <module-option name = "java.naming.provider.url"> ldap://ldap.viralpatel.net:389/</module-option> </login-module> </authentication> </application-policy>
Code language: HTML, XML (xml)
Next step will be to create jboss-web.xml. Create a file jboss-web.xml copy following code in it. And place this file under WEB-INF directory of your project.
<?xml version="1.0" encoding="UTF-8"?> <jboss-web> <security-domain>java:/jaas/website-domain</security-domain> </jboss-web>
Code language: HTML, XML (xml)
Note that, the name website-domain is the security domain and we have specified in application policy of login-config.xml. Now open web.xml from WEB-INF directory of your application and add following code in it.
<security-constraint> <web-resource-collection> <web-resource-name>ADMIN</web-resource-name> <description>An example security config that only allows users with the role ADMIN to access the HTTP servlets </description> <url-pattern>/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>*</role-name> </auth-constraint> </security-constraint> <login-config> <auth-method>BASIC</auth-method> <realm-name>Authentication require</realm-name> </login-config> <security-role> <role-name>*</role-name> </security-role>
Code language: HTML, XML (xml)
To fetch the user details in Java, copy following code in your JSP/Java file.
import java.security.Principal; // Get principal from the request. Principal principal = request.getUserPrincipal(); String userName = principal.getName(); // deal with the userName get from principal.
Code language: Java (java)
Get our Articles via Email. Enter your email address.

You may also like...

23 Comments

  1. bob says:

    So interesting! I couldn’t even guess it might be so exciting!

  2. Aditya says:

    You can use request.getRemoteUser() instead.

  3. guga says:

    Hi,

    One question: what should be the LDAP “structure” for the logins to succeed?

    I mean, how can I tell what DN to use, how to find users, and where are the roles defined in LDAP?

    I can have for example a DN like this:
    uid=jack, ou=people, dc=example, dc=com

    So the user will have attributes in LDAP, the password for example, and the roles … where in LDAP will I define user roles so that JBoss will pick them from the correct attribute?

    Thanks

  4. Naveen says:

    Hi Viral,

    Thanks for such a wonderful site.
    I tried to implement this, but i had no success.
    The authentication window pops up but when i give uid and pwd it doesnot take it.
    After 3 attempts i get 404 error.

    1. I updated server.xml
    2.Update web.xml
    3 .Added jars to commons/lib directory too.

    Thanks,
    Naveen.

  5. dhaval0129 says:

    Hi

    This Tutorial is incomplete and does not help,

    • Marco says:

      Why is it inclomplete what is missing. plz give us details

  6. rd says:

    Viral,

    is the info for implementing ldap still valid for JBOSS AS 7

  7. sanz says:

    @rd I did not find any login-config.xml in JBoss 7. So I am not sure if this tutorial is applicable for AS 7.

  8. murali says:

    hi i am trying to integrate jack rabbit to the jboss .. if u have any idea just post it…. and mail me also…. and i forgot to tell something ur post s are very help full to me at the time of need

  9. RahamaTullah says:

    I am new to LDAP , please explain me in detail, how roles are defined in this concept, and we have to use only jboss ? no other servers we have to use please answer this

  10. Tilak says:

    Hi Viral,

    Have implemented the same in apache successfully. Tested too. But how the same can be done for Websphere 7?

    Can you please tell us in detail?

    Thanks !!!

    • khaleed says:

      Hi Tilak,

      can you please mail me the procedure how did you implement the above code in the apache successfully.

      waiting for your reply.

      T&R,
      Khaleed K

  11. khaleed says:

    Hi Viral,

    I am new to LDAP can you please mail me the steps for the implementation of LDAP.

    Thanks & Regards,
    Khaleed K

  12. ram says:

    Hi Viral,

    I am new to LDAP can you please mail me the steps for the implementation of LDAP.

    Thanks & Regards,
    Ram.

  13. brijesh says:

    not working in eclipse..error of popup is::”A username and password are being requested by http://localhost:8080. The site says: “Please enter your Username””

  14. brijesh says:

    import java.security.Principal;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.struts2.interceptor.ServletRequestAware;
    public class DemoLDAP implements ServletRequestAware{
    	private static HttpServletRequest request;
    	/* (non-Javadoc)
    	 * @see org.apache.struts2.interceptor.ServletRequestAware#setServletRequest(javax.servlet.http.HttpServletRequest)
    	 */
    	public void setServletRequest(HttpServletRequest httpServletRequest) {
    		 this.request = httpServletRequest;
    	} 
    	public static void main(String args[]){
    		Principal principal = request.getUserPrincipal();
    		String userName = principal.getName();
    		System.out.println("userName:::"+userName);
    	}
    }
    


    but this is not working..

  15. komeiming says:

    Hi Viral,
    Could you email a java demo about Configurations in JBoss Server, great thanks.

  16. nitesh says:

    hi Viral
    i wants to implement ldap auth feature in my application which is deployed on tomcat
    and can i use netscape plugin (if it is available for tomcat)
    can you please help me in that.

  17. Praveen says:

    Hi Viral,
    Firstly thanks for the blog and the Post.
    It would have been good if you have specified the JBOSS and Tomcat versions.
    This is becos
    1) in JBOSS 7.1.1 Final the login-config.xml. does not exist.
    2) JBOSS directory naming a structure is different.

    Thanks
    Praveen

  18. VenkateshDeepak says:

    Hi Viral., Thanks for posting.

    When i tried to implement this,., the browser is asking for user name and password credentials.
    Why it is so?

  19. AditiN says:

    I didnt understand what exactly this code does?
    When i includ all code in web application and after that i create war and deploy on jboss it gives me one popup for username and password.. my changes are given below

    login-config.xml
    &lt;application-policy name=&quot;LDAPAuth&quot;&gt;
    	&lt;authentication&gt;
     	&lt;login-module code=&quot;org.jboss.security.auth.spi.LdapExtLoginModule&quot; flag=&quot;required&quot; &gt;
     	&lt;module-option name=&quot;java.naming.factory.initial&quot;&gt;com.sun.jndi.ldap.LdapCtxFactory&lt;/module-option&gt;
     	&lt;module-option name=&quot;java.naming.provider.url&quot;&gt;ldap://localhost:10389&lt;/module-option&gt; &lt;!-- LDAP url--&gt;
     	&lt;module-option name=&quot;java.naming.security.authentication&quot;&gt;simple&lt;/module-option&gt;
     	&lt;module-option name=&quot;bindDN&quot;&gt;cn=Manager,dc=base,dc=com&lt;/module-option&gt; &lt;!-- LDAP user to connect --&gt;
     	&lt;module-option name=&quot;bindCredential&quot;&gt;base123&lt;/module-option&gt; &lt;!-- LDAP password --&gt;
    	&lt;module-option name=&quot;principalDNPrefix&quot;&gt;uid=&lt;/module-option&gt; 
    	&lt;module-option name=&quot;principalDNSuffix&quot;&gt;,ou=People,dc=base,dc=com&lt;/module-option&gt; 
    	&lt;module-option name=&quot;searchScope&quot;&gt;ONELEVEL_SCOPE&lt;/module-option&gt;&lt;!-- Search for groups in all subtrees --&gt;
     	&lt;module-option name=&quot;baseCtxDN&quot;&gt;ou=People,dc=base,dc=com&lt;/module-option&gt;
     	&lt;module-option name=&quot;baseFilter&quot;&gt;(uid={0})&lt;/module-option&gt;
     
    	&lt;module-option name=&quot;rolesCtxDN&quot;&gt;ou=Roles,dc=base,dc=com&lt;/module-option&gt; &lt;!-- context where to search for groups --&gt;
     	&lt;module-option name=&quot;roleFilter&quot;&gt;(member={1})&lt;/module-option&gt; &lt;!-- filter, this searches for groups which have the user set in the attribute 'uniquemember' --&gt;
     	&lt;module-option name=&quot;roleAttributeID&quot;&gt;cn&lt;/module-option&gt;
     	
     	 &lt;module-option name=&quot;roleRecursion&quot;&gt;0&lt;/module-option&gt; &lt;!--how many levels to search recursively inside a group for a user  --&gt;
     	&lt;module-option name=&quot;allowEmptyPasswords&quot;&gt;false&lt;/module-option&gt;
     	&lt;/login-module&gt;
     	&lt;/authentication&gt;
    	&lt;/application-policy&gt;
    
    jboss-web.xml
    
    &lt;jboss-web&gt;
      &lt;security-domain&gt;java:/jaas/base&lt;/security-domain&gt;
    &lt;/jboss-web&gt;
    
    in web.xml
    
      &lt;security-constraint&gt;
          &lt;web-resource-collection&gt;
              &lt;web-resource-name&gt;HtmlAuth&lt;/web-resource-name&gt;
              &lt;description&gt;application security constraints&lt;/description&gt;
              &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
              &lt;http-method&gt;GET&lt;/http-method&gt;
              &lt;http-method&gt;POST&lt;/http-method&gt;
          &lt;/web-resource-collection&gt;
          &lt;auth-constraint&gt;
              &lt;role-name&gt;*&lt;/role-name&gt;
          &lt;/auth-constraint&gt;
      &lt;/security-constraint&gt;
      
      &lt;login-config&gt;
          &lt;auth-method&gt;BASIC&lt;/auth-method&gt;
          &lt;realm-name&gt;LDAPAuth realm&lt;/realm-name&gt;
      &lt;/login-config&gt;
      
      &lt;security-role&gt;
          &lt;role-name&gt;*&lt;/role-name&gt;
      &lt;/security-role&gt;
    
    

    What exactly this code does?
    which username and password i want to put for authentication?
    Kindly do the needful.

  20. dinesh says:

    i had a doubt that is LDAP is protocol or server or else with the combination of application we create the ldap server

  21. Arti says:

    Hi Viral,I want to implement LDAP authentication on Apache tomcat server.I tired with above information provided,but it’s not working.Plzzzzz can you help on this.

Leave a Reply

Your email address will not be published. Required fields are marked *