Thursday 24 September 2015

Restrict user access to servlets and jsps

In this post, I am going to explain how to restrict access to users for all servlet and jsp pages. If user doesn’t login, we just forward the user to login page.

We can achieve this functionality using filters.
As you observe above figure, all the requests should pass through Login filter. Login filter verifies whether user logged in or not. If user logged in it forwards the request to specific servlet/jsp. If the user doesn’t login, it forwards the request to login page.

Following step-by-step procedure explains, complete working application.

Step 1: Create new Dynamic Web Project “hello_world” in Eclipse.


Step 2: Update web.xml like below.
<?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>hello_world</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <session-config>
        <session-timeout>10</session-timeout>
    </session-config>
</web-app>

session time out is set to 10 minutes.

Step 2: Create ‘hello.jsp’ (Right click on the project -> New -> JSP file.).

Give the file name as ‘hello.jsp’.


hello.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>Hello World</h1>
</body>
</html>

Step 3: Create new login.jsp file (Right click on the project -> New -> JSP file.).

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>login page</title>
</head>
<body>
    <form method="post" action="/hello_world/LoginServlet">
        Username: <input type="text" name="username" /> <br /> Password: <input
            type="password" name="password" /> <br /> <input type="submit"
            value="login" />
    </form>
</body>
</html>


Step 4: Create new LoginServlet.java.
Right click on the project -> New -> Servlet.

import java.io.IOException;

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

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if ("admin".equals(username) && "admin".equals(password)) {
            HttpSession session = request.getSession();
            session.setAttribute("admin", "adminstrator");
        } else {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
        }
    }

}


Step 5: Create new Filter LoginFilter.java.
Right click on the project -> New -> 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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebFilter("/*")
public class LoginFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);

        String requestPath = request.getRequestURI();

        if (requestPath.endsWith("login.jsp")
                || requestPath.endsWith("LoginServlet")) {
            chain.doFilter(request, response);
            System.out.println(request.getSession(false));
            return;
        }

        if (session == null || session.getAttribute("admin") == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}

Complete project structure looks like below.


Run the application on server.


it redirects you to the login page. Unless you logged in with credentials (username=admin, password=admin), you can’t access the resources.
Prevoius                                                 Next                                                 Home

No comments:

Post a Comment