j_security_check redirect

BlueChips23 picture BlueChips23 · Mar 2, 2012 · Viewed 15.5k times · Source

I am learning Java servlets on Tomcat environment. I am learning how to use form based login authentication using j_security_check. So, in my servlet, I have a login page that has j_username and j_password. In web.xml file of that servlet, I have the welcome page list indicating my landing page, "landing.html". So, ideally, after successful login, I want the user to get redirected to "landing.html" page.

Without the authentication (no form based authentication), My servlet opens up and goes to "landing.html" page as expected ("localhost:8080/MyServlet" - shows the content of the landing.html).

However, now, after a successful login with j_security_check, for some reason, I get automatically redirected to the .css file for "landing.html" file. I can't understand why is this happening.

Is there a particular way how I can tell the server to just load the "landing.html" page after successful authentication and not forward it to any where else?

EDIT

*Okay, I solved it. The css file which was loading after successful authentication was listed within the <head></head> tags of the login.html page where the j_username and j_password are. I added that css file to make the login page's design consist with the rest of the website. My guess is that when the server is re-loading the wanted resource, for some reason it was simply re-loading the top css file from the head tag. Really weird. So, is j_security_check is the best way to do any authentication for websites on Tomcat or is there a better and more reliable way?*

Answer

JB Nizet picture JB Nizet · Mar 2, 2012

The behavior of form-based authentication is the following:

  • the browser sends a request to a protected URL
  • the server intercepts its request, sees that you're not authenticated, and redirects to the loginf form page
  • the user logs in
  • the server redirects to the URL that triggered the authentication: the protected URL asked in the first step.

This is good, because it allows a user to bookmark a protected page, come back the next day to this bookmarked page, log in, and go directly to the bookmarked page rather than the welcome page.

My guess is that the landing page is not protected, but its CSS file is. So the request that triggers the authenticationis the request that tries to load the CSS file, which causes the user to be redirected to the CSS file.