DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Ensuring Security and Compliance: A Detailed Guide to Testing the OAuth 2.0 Authorization Flow in Python Web Applications
  • A Maven Story
  • Secure Your Web Applications With Facial Authentication
  • 10 Ways To Keep Your Java Application Safe and Secure

Trending

  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  • Measuring the Impact of AI on Software Engineering Productivity
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  1. DZone
  2. Coding
  3. Java
  4. Secure Web Application in Java EE6 using LDAP

Secure Web Application in Java EE6 using LDAP

By 
Mainak Goswami user avatar
Mainak Goswami
·
May. 24, 13 · Interview
Likes (2)
Comment
Save
Tweet
Share
20.1K Views

Join the DZone community and get the full member experience.

Join For Free


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 websitehttp://{samplewebsite.com}/{contextroot}/index.jsp. The webserver goes into the web configuration file and figures out that the requested resource is protected.

web.xml 

Code

<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.











Web application security authentication Java (programming language) Application server

Published at DZone with permission of Mainak Goswami, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Ensuring Security and Compliance: A Detailed Guide to Testing the OAuth 2.0 Authorization Flow in Python Web Applications
  • A Maven Story
  • Secure Your Web Applications With Facial Authentication
  • 10 Ways To Keep Your Java Application Safe and Secure

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!