How to Prevent Browser Back After Logout
I found many problems and questions related to logout/signout. One common problem is that after logout, the browser's Back button allows the user to go back to a previously visited page.
Once a user logs out, they should not be able to access the previously logged-in page without logging in again.
To avoid this problem, we can prevent the browser from using cached copies of protected pages and check whether the user's session is still valid.
Steps
1. Invalidate the Session
When the user logs out, invalidate the session:
session.invalidate();
This removes the session and its associated attributes.
Note: If the application uses other session attributes that must remain available, do not invalidate the session without considering the application's session design. In a normal login/logout flow, however, invalidating the authenticated session is the preferred approach.
2. Set Cache-Control Headers on Protected Pages
Set the following headers on pages that contain protected information:
// Forces caches to obtain a new copy of the page from the origin server
response.setHeader("Cache-Control", "no-cache");
// Prevents the response from being stored in the cache
response.setHeader("Cache-Control", "no-store");
// Causes the cached response to be considered expired
response.setDateHeader("Expires", 0);
// HTTP 1.0 backward compatibility
response.setHeader("Pragma", "no-cache");
You can also combine the Cache-Control directives:
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma", "no-cache");
3. Check the Session Before Showing the Page
Before displaying a protected page, check whether the user is logged in.
For example:
Object facultyList = session.getAttribute("facultyList");
if (facultyList == null) {
response.sendRedirect("index.jsp");
return;
}
// Continue with the normal page processing
This ensures that the application checks the user's session on the server before allowing access to the protected page.
Important Note
The browser's Back button cannot be disabled from a Java/JSP application.
The purpose of these steps is different: after logout, the application should no longer allow access to protected resources, and appropriate cache-control headers help prevent previously viewed protected content from being reused from the browser cache.
For larger applications, authentication checks are usually better handled centrally using a Servlet Filter or a security framework rather than repeating the session check in every JSP page.