Authenticate JBoss application using JAAS and LDAP

It is very easy to connect a JBoss to an LDAP server and creating Java EE applications that use the LDAP information for authorization and authentication. Following these simple steps you will be able to configure your JBoss and a web application (configuring an ejb deployment is similar, just read the Java EE API to map the attributes from web.xml to ejb annotations).

For this example I already have an Apache Directory Server running locally, with the sample LDIF with the sevenSeas company imported. You can find the file and tutorial in the Apache DS documentation.

There are two main steps to be able to use LDAP as an authentication mechanism:

  1. Configure JBoss to connect to LDAP server
  2. Configure the application to use the application policy

Configure JBoss to connect to LDAP server

The JBoss connects to the LDAP server using an application-policy, which is configured in %server_path%/conf/login-config.xml
Just add the following entry in the login-config.xml. You can see the description of the important attributes:

  <application-policy name="ApacheDS">
   <authentication>
   <login-module code="org.jboss.security.auth.spi.LdapExtLoginModule" flag="required" >
   <module-option name="java.naming.factory.initial">com.sun.jndi.ldap.LdapCtxFactory</module-option>
   <module-option name="java.naming.provider.url">ldap://localhost:10389</module-option> <!-- LDAP url-->
   <module-option name="java.naming.security.authentication">simple</module-option>
   <module-option name="bindDN">uid=admin,ou=system</module-option> <!-- LDAP user to connect -->
   <module-option name="bindCredential">secret</module-option> <!-- LDAP password -->
   <module-option name="baseCtxDN">ou=people,o=sevenSeas</module-option>
   <module-option name="baseFilter">(uid={0})</module-option>

   <module-option name="rolesCtxDN">ou=groups,o=sevenSeas</module-option> <!-- context where to search for groups -->
   <module-option name="roleFilter">(uniquemember={1})</module-option> <!-- filter, this searches for groups which have the user set in the attribute 'uniquemember' -->
   <module-option name="roleAttributeID">cn</module-option>
   <module-option name="searchScope">SUBTREE_SCOPE</module-option> <!-- Search for groups in all subtrees -->
   <module-option name="roleRecursion">0</module-option> <!-- how many levels to search recursively inside a group for a user  -->
   <module-option name="allowEmptyPasswords">true</module-option>
   </login-module>
   </authentication>
  </application-policy>

As you can see, the bindCredential is not encrypted. In order to do so, you can check out my post about securing the LdapExtLoginModule

Configure the web application to use the application policy

First, we need to connect the java web application to the application policy defined in JBoss. In order to do this, you need to create the file jboss-web.xml in the WEB-INF folder, the same folder where the web.xml resides.
Here is the content of the file (this works for JBoss 5 in a windows machine, you may need to change the header of the file):

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE jboss-web
    PUBLIC "-//JBoss//DTD Web Application 2.3V2//EN"
    "http://www.jboss.org/j2ee/dtd/jboss-web_3_2.dtd">

<jboss-web>
  <security-domain>java:/jaas/ApacheDS</security-domain>
</jboss-web>

This will tell the container to use the ApacheDS application-policy we defined previously in JBoss.

After this, we only need to restrict the specific urls or servlets to certain roles. In this example, we will only allow access for users in the group “HMS Bounty”, otherwise a 403 (forbidden) will be issued.
In order to do this, we need to edit the web.xml file, adding the following configuration:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <servlet>
  <servlet-name>AServlet</servlet-name>
  <servlet-class>com.app.AServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>AServlet</servlet-name>
  <url-pattern>/AServlet</url-pattern> 
 </servlet-mapping>
 
 <!-- ... more servlets and config ...-->
 
 <security-constraint>
  <display-name>All resources</display-name>
  <web-resource-collection>
   <web-resource-name>All resources</web-resource-name>
   <url-pattern>/*</url-pattern>
  </web-resource-collection>
  <auth-constraint>
   <role-name>HMS Bounty</role-name>
  </auth-constraint>
 </security-constraint>
 <login-config>
  <auth-method>BASIC</auth-method>
 </login-config>

</web-app>

Following this example, you can restrict access to different resources to other roles.

Configure an EJB based WS to use the application policy

If, in turn, you want to secure an EJB based WS, just adding these annotations at the start of the implementing class will do:

@org.jboss.wsf.spi.annotation.WebContext(contextRoot="MyCtxRoot" , authMethod = "BASIC", secureWSDLAccess = false)
@org.jboss.ejb3.annotation.SecurityDomain( "java:/jaas/ApacheDS" )
@RolesAllowed("HMS Bounty")
public class MyWSImplementation implements MyWSInterface{
...

Search LDAP from Java

This post explains how to connect to an LDAP server (in my case Apache DS) and retrieve elements which match a certain filter.

I have deployed an Apache Directory Server version 2.0 and imported the demo LDIF containing users and groups for the “sevenSeas” organization. You can download the file from the apache DS documentation.

This java code connects to the Apache DS deployed locally using the default port and user, and searches the context “ou=groups,o=sevenSeas” for groups the user “Fletcher Christian” belongs to.

import java.util.Properties;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;

public class LdapSearch {
   public static void main(String[] args) throws NamingException {
      InitialLdapContext ctx = constructInitialLdapContext();
      // the name of the context to search
      String contextName = "ou=groups,o=sevenSeas";
      // Filter expression
      String filterExpr = "(uniquemember={0})"; // selects the groups a user belongs to.

      // Filter parameters (name of the user)
      String userDN = "cn=Fletcher Christian,ou=people,o=sevenSeas";
      Object[] filterArgs = { userDN };

      SearchControls constraints = new javax.naming.directory.SearchControls();
      constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); // SUBTREE_SCOPE means recursive search

      NamingEnumeration<SearchResult> search = ctx.search(contextName,
            filterExpr, filterArgs, constraints);
      while (search.hasMoreElements()) {
         System.out.println(search.next().getName());
      }
   }

   private static InitialLdapContext constructInitialLdapContext()
         throws NamingException {
      Properties env = new Properties();
      env.put("java.naming.factory.initial",
            "com.sun.jndi.ldap.LdapCtxFactory");
      // LDAP url
      env.put("java.naming.provider.url", "ldap://localhost:10389");
      // ldap login
      env.put("java.naming.security.principal", "uid=admin,ou=system");
      env.put("java.naming.security.credentials", "secret");

      return new InitialLdapContext(env, null);
   }

}

With the demo LDIF imported in Apache DS the output will be:

cn=HMS Bounty,ou=crews