Secure Web Application in Java EE6 using LDAP

In our previous article we have explained on how to protect the data while it is in transit through Transport Layer Security (TLS)/Secured Socket Layer (SSL). Now let us try to understand how to apply security mechanism for a JEE 6 based web application using LDAP server for authentication.

Objective:
•    Configure a LDAP realm in the JEE Application Server
•    Apply JEE security to a sample web application.

Products used:
IDE: Netbeans 7.2
Java Development Kit (JDK): Version 6
Glassfish server: 3.1
Authentication Mechanism: Form Based authentication
Authentication server: LDAP OpenDS v2.2

Apply JEE security to the sample web application:
The JEE web applications can be secured either through Declarative security or Programmatic security.
Declarative security can be implemented in JEE applications by using annotations or through deployment descriptor. This type of security mechanism is used when the roles and authentication process is simple, when it can make use of existing security providers (even external like LDAP, Kerberos).
Programmatic security provides additional security mechanism when declarative security is not sufficient for the application in context. It is used when we require custom made security and when rich set of roles, authentication is required.

Configure Realm in the Glassfish Application Server
Before we configure a realm in the Glassfish Application server you will need to install and configure an LDAP server which we will be using for our project. You can get the complete instructions in the following article: “How to install and configure LDAP server”.
Once the installation is successful start your Glassfish server and go to the admin console. Create a new LDAP Realm.

Create new LDAP Realm

Create new LDAP Realm

Add the configuration settings as per the configurations set up done for the LDAP server.

Glassfish Web App LDAP Realm

Glassfish Web App LDAP Realm

JAAS Context – identifier which will be used in the application module to connect with the LDAP server. (e.g. ldapRealm)
Directory – LDAP server URL path (e.g. ldap://localhost:389)
Base DN: Distinguished name in the LDAP directory identifying the location of the user data.
Applying JEE security to the web application
Create a sample web application as per the following structure:

SampleWebApp Directory

SampleWebApp Directory

Form based authentication mechanism will be used for authentication of the users.

JEE Login and Authentication

JEE Login and Authentication

Let us explain the whole process with help of above diagram and the code.

Set up a sample web application in Netbeans IDE.

SampleWebApp in Netbeans IDE

SampleWebApp in Netbeans IDE

SampleWebApp Configuration

SampleWebApp Configuration

Step 1:
As explained in the above diagram a client browser tries to request for a protected resource from the website http://{samplewebsite.com}/{contextroot}/index.jsp. The webserver goes into the web configuration file and figures out that the requested resource is protected.

web.xml

<security-constraint>
        <display-name>SecurityConstraint</display-name>
        <web-resource-collection>
            <web-resource-name>Secured resources</web-resource-name>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>GeneralUser</role-name>
            <role-name>Administrator</role-name>
        </auth-constraint>
        <user-data-constraint>
            <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>
</security-constraint>

Step 2:
The webserver presents the Login.jsp as a part of the Form based authentication mechanism to the client. These configurations are checked from the web configuration file.

web.xml

 <login-config>
        <auth-method>FORM</auth-method>
        <realm-name>ldapRealm</realm-name>
        <form-login-config>
            <form-login-page>/Login.jsp</form-login-page>
            <form-error-page>/LoginError.jsp</form-error-page>
        </form-login-config>
</login-config>

Step 3:
The client submits the login form to the web server. When the servers finds that the form action is “j_security_check” it processes the request to authenticate the client’s credential. The jsp form must contain the login elements j_username and j_password which will allow the web server to invoke the login authentication mechanism.

Login.jsp

<form action="j_security_check" method=post>
            <p>username: <input type="text" name="j_username"></p>
            <p>password: <input type="password" name="j_password"></p>
            <input type="submit" value="submit">
            <input type="reset" value="Reset"> 
</form>

While processing the request the webserver will send the authentication request to the LDAP server since LDAP realm is used in the login-config.
The LDAP server will authenticate the user based on the username and password stored in the LDAP repository.

Step 4:
If the authentication is successful the secured resource (in this case index.jsp) is returned to the client and the container uses a session id to identify a login session for the client. The container maintains the login session with a cookie containing the session-id. The server sends this cookie back to the client, and as long as the client is able to show this cookie for subsequent requests, then the container easily recognize the client and hence maintains the session for this client.

Step 5:
Only if the authentication is unsuccessful the user will be redirected to the LoginError.jsp as per the configuration in the web.xml.

<form-error-page>/LoginError.jsp</form-error-page>

This shows how to apply form based security authentication to a sample web application. Now let us get a brief look on the secured resource which is used for this project.
In this project the secured resource is index.jsp which accepts a username and forwards the request to LoginServlet. Login servlet dispatches the request to Success.jsp which then prints the username to the client.

 index.jsp

 <body>
        <h2>Please type your name</h2>
        <form method="POST" action="LoginServlet">
            <input type="text" name="username" size="25">
            <p></p>
            <input type="submit" value="Submit">
            <input type="reset" value="Reset">
        </form>
 </body>

LoginServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            RequestDispatcher requestDispatcher = getServletConfig().getServletContext().
                    getRequestDispatcher("/Success.jsp");
            requestDispatcher.forward(request, response);
        } finally {
            out.close();
        }
    }

Success.jsp

<body>
        <h1>You have been successfully logged in as ${param.username}</h1>
</body>

Web.xml

<servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.login.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
 </servlet-mapping>

You can download the complete working code from the below link.

SampleWebApp-Code Download

Hope our readers have enjoyed this article. Keep watching this space for more articles on JEE security.

11 Responses to “Secure Web Application in Java EE6 using LDAP”

  1. Michael R.

    Jul 14. 2013

    This is a good article. A good follow up would be demonstrating how to define your own security realms to do more complicate user authentication. Typically users can authenticate in multiple ways to the same application and one of the apparent limitations of Java EE security is all authentication needs to be performed on a pre-defined realm.

    Reply to this comment
    • IdioTechie

      Jul 15. 2013

      Thanks Michael for reading this article and for providing your input. I will write as per your request in the next series. Please keep watching this space.

      Reply to this comment
      • Arjan Tijms

        Jul 31. 2013

        As you may know there are two options for doing that; using GlassFish specific modules, or using the Java EE standard ones (JASPIC).

        It would be great if you could write your follow-up article using JASPIC.

        Reply to this comment
  2. Arjan Tijms

    Jul 31. 2013

    >one of the apparent limitations of Java EE security is all authentication needs to be performed on a pre-defined realm.

    This is not entirely true. Via the JASPIC standard, which is part of Java EE 6 and 7 and for which GlassFish has excellent support, you can programmatically register an auth module. Meaning that there’s no pre-defined realm needed anywhere.

    Your own auth module could then (optionally) delegate to different modules or use different methods for the actual authentication.

    I wrote an article about this some time back, see http://arjan-tijms.blogspot.com/2012/11/implementing-container-authentication.html

    Reply to this comment
  3. Misael.A

    Jan 12. 2014

    Excellent guide, I was a lot of utility. About the comment Arjan, JASPIC is similar to OpenDS or is it? I’m new to this. Sorry for my bad drafting in English, I speak Spanish.

    Reply to this comment
  4. vivek

    Apr 04. 2014

    I have screenshot of my error application with ldap. Wanna send the same screenshot to you.Is there any mail id to send .?

    Reply to this comment

Trackbacks/Pingbacks

  1. How to install and configure LDAP server? | IdioTechie - May 20, 2013

    […] our next series we will try to explore how to use the LDAP server from JEE applications and apply security features in JEE based web application. Keep watching this […]

  2. Java Security Tutorial - Step by Step guide to create SSL connection and certificates | IdioTechie - June 10, 2013

    […] our series of articles on applying JEE security we present you another detailed tutorial on how to create a SSL connection and create certificates […]

Leave a Reply