Java session filters with users and admin

In my web application I have 2 main sections

  • User
  • Administrator

I am using a java session filter to check the user's session and allow access to a specific part of the website. Consequently, the user only has access to sections of the custom pages, while the administrator has access to the administration section.

The session filter for users is already implemented and works fine. it checks for user (username and password from database - mysql) and gives access to restricted subfolder where i have xhtml pages.

if i need filters to authenticate in admin section (admin username and password are stored in db) and allow them to access based on their user level.

do I need to create 1 more filter - admin?

Currently, here's my user implementation:

package com.shadibandhan.ControllerLayer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Cookie;

/**
 *
 * @author MUDASSIR
 */
public class SessionFilter implements Filter {

    private ArrayList<String> urlList;
    private String toGoTo = null;
    private boolean userCookieExists = false;

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

        System.out.println("****************************************");
        System.out.println("***Session Filter Servlet initialized***");
        System.out.println("****************************************");
        String urls = config.getInitParameter("avoid-urls");
        System.out.println("The urls to avoid are = " + urls);
        StringTokenizer token = new StringTokenizer(urls, ",");

        urlList = new ArrayList<String>();

        while (token.hasMoreTokens()) {
            urlList.add(token.nextToken());

        }
    }

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

        System.out.println("This is the doFilter method");

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String contextRelativeURI = null;
        String contextRelativeURIForAdmin = null;



            contextRelativeURI = request.getRequestURI().substring(request.getContextPath().length());


        String contextPath = request.getContextPath();
        String remoteHost = request.getRemoteHost();
        String url = contextPath + contextRelativeURI;
        System.out.println("-----------------> Servlet path is = " + contextRelativeURI);
        System.out.println("-----------------> Context path is " + contextPath);
        System.out.println("-----------------> URL is " + url);
        System.out.println("-----------------> Remote Host is " + remoteHost);
        boolean allowedRequest = false;

        if (urlList.contains(contextRelativeURI)) {
            allowedRequest = true;
        }

        if (!allowedRequest) {
            HttpSession session = request.getSession(false);
            if (null == session) {

                System.out.println("Session is not present");
                response.sendRedirect(contextPath);
                return;

            }
            if (null != session) {

                System.out.println("Session is present");
                System.out.println("\nSession no. is = " + session.getId());

                if (session.getAttribute("logged-in") == "true") {
                    System.out.println("Session logged-in attribute is true, " + session.getAttribute("sessionUsername") + " is logged in.");



                        RequestDispatcher dispatcher = request.getRequestDispatcher(contextRelativeURI);
                        dispatcher.forward(request, response);
                        return;
                } else {
                    System.out.println("Session logged-in attribute is not true");
                    response.sendRedirect(contextPath);
                    return;
                }
            }
        }

        chain.doFilter(req, res);
    }

    @Override
    public void destroy() {
    }
}

      

This is my web.xml mapping for the filter

<filter>
        <filter-name>SessionFilter</filter-name>
        <filter-class>
            com.shadibandhan.ControllerLayer.SessionFilter
        </filter-class>
        <init-param>
            <param-name>avoid-urls</param-name>
            <param-value></param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>SessionFilter</filter-name>
        <url-pattern>/com.shadibandhan.Restricted/*</url-pattern>
    </filter-mapping>

      

Now I also put admin pages in a restricted folder? or do I put them in another separate folder? I have also seen the servlet authentication method mentioned here that recommends changes to the tomcat-users.xml file, but I have usernames and passwords in the db.

Please suggest recommended methods.

0


source to share


1 answer


The best way to secure your web application is to use container-managed authentication , so your application doesn't need to handle the authentication and authorization mechanism. This mechanism is called JAAS in the Java world.

Using container-managed authentication usually requires some configuration in the servlet application - in addition to the changes required in your web application - but you'll be more secure. Since you said you are using Tomcat, I will give you the best answer I can use on this servlet container, others are configured in a different way.

1. Configure the Tomcat realm

First of all, forget about tomcat-users.xml

(this is not secure) and decide how are you going to store your authentication data, LDAP server? database? what database ?. Once you have decided, you will need to modify your server.xml

file in the folder conf

in Tomcat to add a new realm . The type of kingdom you create will depend on your previous decision.

And let's point out the obvious: add users to the repository.

2. Configuring the web application

Now, you need to configure the authentication method on the side of your web application. This is done to modify the file web.xml

in /WEB-INF

.



You can choose Basic authentication or Forms-based authentication . I prefer to use the latter as it allows me to provide a customized form to end users.

Some of the links I provide here describe the process step by step. They also include information on how to restrict access to parts of your application to different users, that is:

<security-constraint>
  <web-resource-collection>
    <web-resource-name>AdminPages</web-resource-name>
    <description> accessible by authorised users </description>
    <url-pattern>/admin/*</url-pattern>
    <http-method>GET</http-method>
  </web-resource-collection>
  <auth-constraint>
    <description>These are the roles who have access</description>
    <role-name>ADMIN</role-name>
  </auth-constraint>
</security-constraint>

      

3. User knowledge

After this configuration, your application should know the username using the method getRemoteUser()

in HttpServletRequest

.

EDIT:

I would suggest using the same table for admins and users and just make the difference between the two using roles. If your object admin

needs additional fields that shouldn't be available to regular users, then link both tables and just refer to admin

when it HttpServletRequest.isUserInRole("ADMIN")

returns true

.

0


source







All Articles