0

I'm creating a website with HTML/CSS/Javascript/JSP and Tomcat v10 Java Servlets and have built a login system that creates a HttpSession once the user signs in. Even though this dynamically removes the login button, there is nothing stopping that user from copying and pasting the url to the login page.

Is there an effective way to immediately redirect to a different html file if a session does not exist? I saw some other posts using PHP but I've never used that technology and was hoping there is a diff way.

TTT
  • 186
  • 1
  • 11

2 Answers2

0

As far as I know, url to the JSP is treated like a request to the server

You can use a Filter for it.

Filter is for pre and post processing a request, you can use it to check if inbound request have session or not

Something like this:

HttpServletRequest httpRequest = (HttpServletRequest)request;
    HttpServletResponse httpResponse = (HttpServletResponse)response;
    HttpSession session = httpRequest.getSession();
    AdUser user = (AdUser)session.getAttribute("user");
    if (user == null) {
        httpRequest.setAttribute("errorMessage", "You must login first");
        httpRequest.getRequestDispatcher("Authenticate.jsp").forward(request, response);
    } else {
        chain.doFilter(request, response);
    }
  • That makes sense, thank you. But how would I specify which servlet is handling this though? I know for you specify a but do I need to add somewhere in my JSP file which servlet doGet method will be performing this? – TTT Nov 19 '21 at 04:05
  • @TTT yes, in your specific case, method is get, then you can replace getRequestDispatcher with a sendRedirect to a servlet – Le Programmeur Nov 19 '21 at 04:51
0

Instead of creating homegrown filter you should utilize Java EE security API

Create security constraint that will only allow authenticated users to access given parts of the application. In that case server will make sure that unauthenticated users cannot access given pages.

You could use opensource OpenLiberty server which fully implements Java EE API, if Tomcat is not implementing that spec fully.

Something like (not complete code just a sample to give you an idea):

<!-- SECURITY CONSTRAINT -->
<security-constraint>
    <web-resource-collection>
        <web-resource-name>protected pages</web-resource-name>
        <url-pattern>/html/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>AUTH_USER</role-name>
    </auth-constraint>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>
<login-config>
    <auth-method>FORM</auth-method>
    <realm-name>file</realm-name>
    <form-login-config>
        <form-login-page>/login.jsp</form-login-page>
        <form-error-page>/error.jsp</form-error-page>
    </form-login-config>
</login-config>
....
Gas
  • 17,601
  • 4
  • 46
  • 93