springspring-bootspring-security

Spring Boot doesn't redirect unauthenticated users to login page when accessing index


I am working on a web application that uses form-based login and some OAuth2 integrations (GitHub and Google login), although the problem isn't with the authentication methods themselves, but with the authorized requests in Spring's SecurityFilterChain.

I have the following Spring Boot security configuration:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
            // Explicitly enable form login and specify the login page to be mapped at "/login"
            .formLogin(form -> form.loginPage("/login").permitAll())
            .oauth2Login(form -> form.loginPage("/login").permitAll())
            .logout((logout) -> logout.logoutUrl("/logout").logoutSuccessUrl("/").permitAll())

            // Specify required authentication levels for URL mappings
            .authorizeHttpRequests(authorize -> authorize
                    .requestMatchers("/login/**").anonymous()
                    .requestMatchers("/register/**").anonymous()
                    .requestMatchers("/events/**").authenticated()
                    .requestMatchers("/").authenticated()
                    .anyRequest().permitAll());

    return http.build();
}

... where I explicitly allow unauthenticated users to send requests to every endpoint of my web application, except for the events page (/events/**) and for the index page (available at the endpoint /). The index page is available at localhost:8080.

However, when I'm not logged in on my web application, I can still access the index page, the controller automatically redirecting me to the defined template in the controller (I don't feel the need to include other code here, as it doesn't help with my problem).

The login page is properly defined, as if I want to explicitly deny some other endpoint, I get correctly redirected to localhost:8080/login. In this case, the third defined request matcher (/events/**) works properly.

Using /** as a request matcher still does not fix the job.

What should I change in my current security configuration, in order for unauthenticated users to get redirected to the /login page, when navigating to the index / endpoint?


Solution

  • Maby because of this line? .logout((logout) -> logout.logoutUrl("/logout").logoutSuccessUrl("/").permitAll()) so in my understanding (sorry its late) you permit everyone to access "/"