Skip to content

spring boot security prevent the logged in user from seeing the login and registration pages

I am using Thymeleaf in the interface layer. I want to prohibit login and register pages when user is logged in. Is there any solution to this?

    @Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/persons/**","/animals/**","/animal/**","/person/**")
            .hasRole("USER")
            .antMatchers("/**")
            .permitAll()
            .and()
            .formLogin()
            .loginPage("/login")
            .loginProcessingUrl("/dologin")
            .defaultSuccessUrl("/persons")
            .and()
            .logout()
            .logoutUrl("/logout")
            .logoutSuccessUrl("/login")
            .and()
            .csrf()
            .disable();

}

Advertisement

Answer

To enforce this, you can enable anonymous access (e.g. required to be anonymous to access this resource). See Common Built-In Expressions for a description of anonymous vs authenticated. You can use something like this:

http.authorizeRequests((authorizeRequests) -> authorizeRequests
  .mvcMatchers("/register", "/login").anonymous()
  .anyRequest().authenticated()
)
User contributions licensed under: CC BY-SA
1 People found this is helpful