In this short Spring Security post, I would like to share with you a simple way to prevent a user from going back to login page if he already logged in a web application based on Java Spring Boot.

A typical scenario is that a user has just logged in to the website and somehow he clicks the Back button in the browser unintentionally (or type the /login URL). Spring Security doesn’t handle this situation, so we need to write a little bit extra code, e.g. redirecting the logged-in user to the homepage in case he accidentally visits the login page again.

Suppose that you configure Spring Security to use a custom login page at the /login URL in the Spring security configuration class as below:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
			...
			.formLogin()
				.loginPage("/login")				
				.permitAll()
			...
	}
}
And to prevent the user from going back to the login page if he already logged in, you need to write a simple handler method for the /login URL in a Spring MVC controller as follows:

@Controller
public class AppController {
	
	@GetMapping("/login")
	public String showLoginForm(Model model) {
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
			return "login";
		}

		return "redirect:/";
	}
}
You see, in this handler method, we get an Authentication object that represents an authenticated user from Spring security context. If this object is null or is an instance of AnonymousAuthenticationToken, that means the user has not logged in, then it will return the login page. Otherwise it will return the homepage. Clear and simple, right?

To see the coding in action, you can watch the following video:

 

Related Spring Security Tutorials:

 

Other Spring Boot Tutorials:



 


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment

   


Comments 

#1J2022-06-15 15:32
How would you prevent a logout user to hit the back button and get a private page?
Spring Security is supposed to handle that, but it doesn't actually when customizing the login page
Quote