Search code examples
spring-boothttp-redirectspring-securityconfigurationjava-17

getting TOO_MANY_REDIRECTS when attempting to access localhost:8080 with Spring Security


Using last version of spring. I've followed this guide step by step, checked it again and again, but I'm seeing this when I try accessing localhost:8080:

enter image description here

Here's my WebConfig class:

@Configuration
@EnableWebSecurity
public class WebConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(requests -> requests
                        .requestMatchers("/", "/home").permitAll()
                        .anyRequest().authenticated()
                )
                .formLogin(form -> form
                        .loginPage("/login")
                        .permitAll()
                )
                .logout(LogoutConfigurer::permitAll);
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user =
                User.withDefaultPasswordEncoder()
                        .username("user")
                        .password("password")
                        .roles("USER")
                        .build();
        return new InMemoryUserDetailsManager(user);
    }
}

Together with the 3 html files: enter image description here

I've searched for this throughout the entire web and found no solution. Is there anything the guide or I am missing? There's no controller or mapping whatsoever inside the code. Just the webconfig and static files.

P.s. I see no Spring Security password being generated when starting up the app: enter image description here

is this a normal thing?


Solution

  • /login HTTP.GET mapping is not being resolved by any MVCController.

    Add a folder named controller and create a MVCController.java file inside it with the following content:

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class MVCController {
    
        private static final Logger LOG = LoggerFactory.getLogger(MVCController.class);
    
        @GetMapping(value = "/login")
        public String login() {
            LOG.info("/login");
    
            LOG.info("Return login");
    
            //return login.html located in /resources/templates
            return "login";
        }
    }
    

    After adding this, when you go the http://localhost:8080, the login page should be presented.