Table of contents
1.
Introduction
2.
Security in JSP
3.
Role-Based Authentication
4.
Form-Based Authentication
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

Security in JSP

Author Tanay kumar Deo
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The security of a web application is one of the most critical aspects, and it cannot be compromised, especially for web apps dealing with sensitive user information. We have two important aspects of security in JSP ( Java Server Pages ):

  • To prevent unauthorized/fake users from accessing sensitive information.
  • Preventing hackers/attackers from accessing data on the web.

 

This article will discuss different approaches to achieve security in JSP. We will implement several levels of authentications and authorizations. So, let's get started with the article.

Security in JSP

An insecure JSP web page can put at risk some or all of the servers, the networks on which this server is residing, the client accessing the web page, and possible worm distribution attacks and DDoS (Distributed denial of service). Hence, security in JSP is one of the most critical aspects.

We will follow these two approaches to achieve the security of the JSP web application.

  • Declarative security:- In this approach, we will not write any code to achieve security in JSP. Instead, all the configurations are done in the deployment descriptor (web.xml).
  • Programmatic security: The request object provides methods that we may use to authenticate the users programmatically.

Role-Based Authentication

The authentication mechanism in JSP uses a technique called role-based security. The idea behind this technique is that rather than restricting the resources at the user level, we can create roles and limit the resources based on roles.

We may define different user roles in the tomcat-users.xml file, which is located off Tomcat home directory in conf. An example of the file is shown below.

<?xml version = '1.0' encoding = 'utf-8'?>
<tomcat-users>
   <role rolename = "user"/>
   <role rolename = "userrole1"/>
   <role rolename = "manager"/>
   <role rolename = "admin"/>
   <user username = "user" password = "password" roles = "user"/>
   <user username = "userrole1" password = "password" roles = "userrole1"/>
   <user username = "both_roles" password = "tomcat" roles = "user,userrole1"/>
   <user username = "admin_manager" password = "secret" roles = "admin,manager"/>
</tomcat-users>

 

A simple mapping between usernamepassword, and roles is shown in the above code. We can note that one user can have multiple roles. For example, username ="both_roles" have two roles "user" as well as "userrole1".

Once we have identified and defined different user roles, we can place role-based security restrictions on various web application resources with the help of the <security-constraint> element in the web.xml file available in the WEB-INF directory.

<web-app>
   ...
   <security-constraint>
      <web-resource-collection>
                <web-resource-name>SecurityInJSP</web-resource-name>
                <url-pattern>/manager/*</url-pattern>
                <http-method>GET</http-method>
                <http-method>POST</http-method>
      </web-resource-collection>
      
      <auth-constraint>
                <description>
                          Only managers can use this app
                </description>
                <role-name>manager</role-name>
      </auth-constraint>
   </security-constraint>
   
   <security-role>
      <role-name>manager</role-name>
   </security-role>
   
   <login-config>
      <auth-method>BASIC AUTH</auth-method>
   </login-config>
   ...
</web-app>

 

The above code would mean −

  • Any HTTP POST or GET request to a URL matching by /manager/* will be subject to the security restriction.
  • A user with the role= “manager” is given access to the manager resources.
  • We use the login-config element to describe the BASIC AUTH form of authentication.

 

If we try browsing any URL, including the /manager directory, a dialogue box will be displayed asking for the username and password. If we provide a username = "admin" and password = "secret", we will have access to the URL matching by /manager/* as we have defined the user admin with the manager role.

Form-Based Authentication

When we use the FORM-based authentication method for security in JSP, we must supply a login form to prompt the user for the username and password. This helps us identify the user, and also, we may restrict using some form for users with different roles. Following is a simple code for login.jsp.

<html>
   <body bgcolor = "#ffffff">
      
      <form method=”POST” class="container">
            <label for="uname"><b>Username</b></label>
            <input type="text" placeholder="Enter Username" name="j_username" required>


            <label for="psw"><b>Password</b></label>
            <input type="password" placeholder="Enter Password" name="j_password" required>
        
            <button type="submit">Login</button>
    </div>
      
   </body>
</html>
You can also try this code with Online Java Compiler
Run Code

 

Now that we have successfully built our login form, let’s modify the <login-config> element to specify the auth-method as the FORM −

<web-app>
   ...
   <security-constraint>
      <web-resource-collection>
         <web-resource-name>SecurityInJSP</web-resource-name>
         <url-pattern>/manager/*</url-pattern>
            <http-method>POST</http-method>
            <http-method>GET</http-method>
      </web-resource-collection>
      
      <auth-constraint>
         <description>Only managers can use this app</description>
         <role-name>manager</role-name>
      </auth-constraint>
   </security-constraint>
   
   <security-role>
      <role-name>manager</role-name>
   </security-role>
   
   <login-config>
      <auth-method>FORM</auth-method>
      <form-login-config>
         <form-login-page>/login.jsp</form-login-page>
         <form-error-page>/error.jsp</form-error-page>
      </form-login-config>
   </login-config>
   ...
</web-app>
You can also try this code with Online Java Compiler
Run Code

 

When we try to access a resource with URL /manager/*, it will display the above form asking for the username and password. We will have access to the URL matching by /manager/*on successful login. And if the login fails, the server will send back the form-error page. 

Programmatic Security in JSP

The HttpServletRequest object provides many methods that can be used to get security information at runtime. These methods are shown in the table below:

Method

Description

String getAuthType() This method returns a string that represents the name of the authentication used to protect the JSP.
boolean isUserInRole(java.lang.String role) This method returns a boolean value true if the user has the given role or false if not.
String getProtocol() This method returns a string object representing the protocol used to send the request. We may use this value to check if a secure protocol was used or not.
boolean isSecure() This method returns a boolean value (true or false) representing whether HTTPS made the request.
Principle getUserPrinciple() This method returns a java.security.Principle object, which contains the name of the currently authenticated user.

 

We can use the above methods for programmatic security in JSP. For example:

<% if ( request.isUserInRole( "manager" ) ) { %>
   <a href = "managers/dashboard.jsp">Manager Dashboard</a>
   <a href = "managers/personnel.jsp">Personnel Records</a>
<% } %>
You can also try this code with Online Java Compiler
Run Code

 

In the above code, we checked if the user has role = "manager" programmatically.

FAQs

  1. What is j_security_check in JSP?
    j_security_check is an action that JSP applications using form-based login have to specify for the user login form. In the same form, we should also have the text input control known as j_username and a password input control known as j_password.
     
  2. What are the authentication mechanisms for security in JSP?
    There are various authentication mechanisms to secure our JSP web application. Some of them are as follows:
    HTTP Basic Authentication
    Form-based Authentication
    Digest Authentication
    Client Authentication
     
  3. What are the requirements for Form-based authentication for security in JSP?
    While creating a form-based authentication in JSP we must implement the following security measures to make our JSP application secure:
    The security is based on role. So, we must define and use <security-role> in our web.xml.
    We must configure our web.xml file with <security-constraint> and <login-config>.
     
  4. What is the use of <security-constraint> in the web.xml file for the JSP application?
    In the web.xml file of JSP, <security-constraint> tag defines web resource collection in which the URL pattern is defined. This is the URL pattern for where security will be applied and the login page will be displayed.

Key Takeaways

JSP is a powerful technology and must be handled with secure and reliable operation of the application. This article taught us different methods to chive security in JSP using authentication mechanisms. We also discussed Declarative Security and Programmatic security.

Don't stop here. Check out the blogs Introduction to JSPJSP - Custom TagsJSP Architecture and Lifecycle and JSP Syntax and First App.

We hope you found this blog helpful. Liked the blog? Then feel free to upvote and share it.

Live masterclass