Control User Page Access with a Java Filter

How to Control User Page Access with Java Filters

October 15, 2016


A Quick Summary: When a user is using your web application, there may be pages that you do not want them to access based on whether they are logged in or not. With this post, I will explain how using a Java Filter can monitor and restrict a user’s access to certain pages.

Overview:
How a Java Filter Works
The Barebones of a Java Filter
Writing the Control User Page Access Java Filter (The Code)

How a Java Filter Works

A Java filter will intercept a request to a servlet, evalute the request, and then redirect the request according to what the filter was designed for. To make understanding it a bit simpler we will look at a filter in three pieces: Mapping, Evaluating Parameters, and Redirecting.

Mapping a Java Filter

Mapping a filter can be done in a total of three ways, each up to you to choose, but never more than one for the same filter. The three ways are: Using the Deployment Descripter (the web.xml file), Using Annotations, and programmaticly. In the example below, we will be using the deployment descriptor.

The purpose of mapping is to designate which pages the filter will watch. For example, you wouldn’t want an unauthenticated user accessing a ‘bank account’ without having gone through the login process. To prevent this, you would map a Java Filter to that ‘bank account’ page in which it would check to see if the user has logged in and then redirect them the ‘login’ page if they haven’t. In addition, you can map a filter to as many pages as you like.

Evaluating Parameters

Once a filter knows what page to look at for requests, the filter will evaluate a request based on the developers set parameters. In the example below, we will check to see if the user has logged in by evaluating a ‘isLoggedIn’ boolean value.

Redirecting

Redirecting consists of sending the user of your application to a particular based of the results of the evaluated parameters. This is done with the HTTPResponse object and its method ‘sendRedirect()’ with the url of the desired page set for its parameter.

The Barebones of a Java Filter

A Java Filter comes with three methods: ‘init()’, ‘doFilter()’, and ‘destroy()’.

The ‘init’ method is called immediately after the Java Filter has been instantiated and the ‘destroy’ method will carry out any last minute details before the filter is taken out.

The ‘doFilter’ method is where all of the magic happens. It is in this method that you will test for certain conditions that will then decide where you will redirect the user.

Writing the Control User Page Access Java Filter

Overview:

loginPage.jsp
loggedInPage.jsp
User Authentication Servlet
User Page Access Control Filter
web.xml

The Login Page

The login page is fairly straight forward JSP page. We will create an html form with two attributes, method and action. The method will be POST and the action will send the request to our UserAuthenticationServlet with two parameters: ‘username’ and ‘password’ which are designated with the name attribute in the input elements.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>

<form method="POST" action="${pageContext.request.contextPath}/UserAuthenticationServlet">
	<p>Enter UserName:</p>
	<input type="text" name="username"/>
	<p>Enter Password:</p>
	<input type="password" name="password"/>
	<button type="submit">Login</button>
</form>

</body>
</html>

 

The Logged In Page

This is another JSP page. If the user successfully logs in, then this page will load with a simple welcome message.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
	<h1>You have successfully logged in.</h1>
</body>
</html>

 

The User Authentication Servlet

The purpose of this servlet is to check the request parameters to see if they match the “database”, which is just two Strings, ‘username’ and ‘password’. If the parameters match the String values, then we will create a new session attribute ‘username’. This attribute is what our Java Filter will check for to allow or redirect the user to the correct page.

We also have a boolean variable ‘isLoggedIn’, which will be tessted to direct where the user is supposed to go in the first place.

The UserAuthenticationServlet code:

package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class UserAuthenticationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		
		boolean isLoggedIn = false;
		HttpSession session = req.getSession();
		
		if(username.equals("weston") && password.equals("westonPass")){
			isLoggedIn = true;
			session.setAttribute("username", username);
		}
		
		if(isLoggedIn == true){
			res.sendRedirect("loggedInPage.jsp");
		}else{
			res.sendRedirect("loginPage.jsp");
		}
	}
}

 

User Page Access Control Filter

All of the logic for this Java Filter is within the ‘doFilter’ method. The major areas to focus on are: getting the HttpSession attribute, testing the attribute, redirecting the user, and the essential doFilter method.
 
The HttpSession Attribute

If you recall from the UserAuthenticationServlet, we created a String HttpSession attribute named, ‘username’, which was set to the username parameter value from the login screen. Here, we are going to ‘get’ that ‘attribute’ from the HttpSession and set it to a String variable called ‘sessionUsername’.
 
a)Create a new HttpSession object and set it to the current HttpSession.

a)HttpSession session = req.getSession();

 
b) Get the ‘username’ HttpSession attribute and set it to a String variable.

b) String sessionUsername = (String)session.getAttribute("username");

 
c) Test the new String variable ‘sessionUsername’ to see if it is null or not. You may be wondering why we are not testing to see if the String ‘sessionUsername’ is equal to “”. The reason for this is because if the user didn’t pass through the UserAuthenticationServlet successfully, then there was never an HttpSession created. This means the ‘username’ attribute was never created, leaving us with nothing to test against. That translates into a Null Pointer Exception.

c) if(sessionUsername == null){

 
d) If the ‘sessionUsername’ is null, then we will redirect the user back to the ‘loginPage.jsp’ using the HttpResponse method ‘sendRedirect’.

d) res.sendRedirect("loginPage.jsp");  }

 
e) Call the FilterChain’s method doFilter to finish off the filter. A Filter Chain is like a series of Java Filters, so when one filter has been carried out, this ‘chain.doFilter’ will move to the next filter in the series.

e) chain.doFilter(request, response);

 
The UserPageAccessControl Filter Code:

package filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class UserPageAccessControl implements Filter {

	public void init(FilterConfig fConfig) throws ServletException {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		HttpSession session = req.getSession();
		
		String sessionUsername = (String)session.getAttribute("username");
		
		if(sessionUsername == null){
			System.out.println("Access not allowed."); //SO WE KNOW THE FILTER FIRED
			res.sendRedirect("loginPage.jsp");
		}
		
		chain.doFilter(request, response);
	}

	public void destroy() {
	}

}

 

The web.xml file (Deployment Descriptor)

 
Filter Mapping

The filter mapping is composed of two main elements and their sub-fields: ‘filter’ and ‘filter-mapping’.
 
‘filter’ – this provides your Java Filter with a name that will be referenced in ‘filter-mapping’ as well as where the filter class is located.

<filter>
<filter-name>UserPageAccessControl</filter-name>
<filter-class>filter.UserPageAccessControl</filter-class>
</filter>

 
‘filter-mapping’ – we will reference the filter name from ‘filter’ and then set a ‘url-pattern’. The pages that you want to Java Filter to be applied to are what goes inside the ‘url-pattern’. Since we want to prevent an unauthenticated user from accessing the ‘loggedInPage.jsp’, we will put that inside the ‘url-pattern’.

<filter-mapping>
	<filter-name>UserPageAccessControl</filter-name>
	<url-pattern>/loggedInPage.jsp</url-pattern>
</filter-mapping>

 
The full ‘web.xml’ code:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>UPACJ</display-name>
	<welcome-file-list>
		<welcome-file>loginScreen.jsp</welcome-file>
	</welcome-file-list>

	<servlet>
		<servlet-name>UserAuthenticationServlet</servlet-name>
		<servlet-class>servlet.UserAuthenticationServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>UserAuthenticationServlet</servlet-name>
		<url-pattern>/UserAuthenticationServlet</url-pattern>
	</servlet-mapping>
	
	<filter>
		<filter-name>UserPageAccessControl</filter-name>
		<filter-class>filter.UserPageAccessControl</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>UserPageAccessControl</filter-name>
		<url-pattern>/loggedInPage.jsp</url-pattern>
	</filter-mapping>
</web-app>

That wraps it up for this Java Filter tutorial, “How to Control User Page Access with Java Filters”. Happy Coding!