Enterprise Java

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:

 

Reference: Secure Web Application in Java EE6 using LDAP from our JCG partner Mainak Goswami at the Idiotechie blog.

Mainak Goswami

Mainak Goswami is an experienced Technology Consultant specializing in JEE, Web Development and Open source technologies. He is currently based out of United Kingdom. He is a technology enthusiast trying to explore the latest in the world of technology. His current area of interest is Mobility, NoSQL and Cloud computing. In past time he loves blogging on his website Idiotechie.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Venkata Gutta
Venkata Gutta
5 years ago

hi , I have java web application using netBeans 8.2, I want to authenticate with active Directory,can you please share the source code.

Back to top button