Search code examples
springspring-bootspring-mvcspring-security

Can't resolve some of the deprecated methods of Spring Security like and() and formLogin()


I am creating a project using Spring and I am facing some issues. I see many of the methods have been deprecated and I have updated them by searching on net but I am facing trouble with "and()" and "formLogin()". Someone please help.

Here's my code in which I have updated some of the deprecated methods :

public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((authz) -> authz
                        .requestMatchers(
                "/registration**",
                        "/js/**",
                        "/css/**",
                        "/img/**").permitAll()
                .anyRequest().authenticated()
                        .and()
                        .formLogin()
                        .loginPage("/login")
                        .permitAll()
                        .and()
                        .logout(Customizer.withDefaults())
                        .invalidateHttpSession(true)
                        .clearAuthentication(true)
                        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                        .logoutSuccessUrl("/login?logout")
                        .permitAll()

        )
                .httpBasic(withDefaults());
        return http.build();
    }

But it has error in "and()" and "formLogin()" and I couldn't figure out how to solve this. This is the error its showing :

'and()' is deprecated and marked for removal

'formLogin()' is deprecated and marked for removal

Please fix it.


Solution

  • Based on Migration Guide and What’s New in Spring Security 6.1 and also Deprecated-List, you configuration should look so:

     @Bean
      public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                .requestMatchers(
                    "/registration**",
                    "/js/**",
                    "/css/**",
                    "/img/**").permitAll()
                .anyRequest().authenticated());
        http.formLogin(fL -> fL.loginPage("/login").permitAll());
        http.logout(lOut -> {
          lOut.invalidateHttpSession(true)
              .clearAuthentication(true)
              .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
              .logoutSuccessUrl("/login?logout")
              .permitAll();
        });
        http.httpBasic(withDefaults());
        return http.build();
      }
    

    For more information i really suggest you to read\check the above attached references.