1
resposta

Como criar o método AuthenticationManagerBuilder com o Spring 2.7 ?

Não consigo fazer @Override no configure(AuthenticationManagerBuilder auth) na versão 2.7.2 do Spring (acredito que tenho que injetar alguma dependência, @BEAN). Alguém consegue me ajudar?

(package e imports omitidos)

@Configuration @EnableWebSecurity public class WebSecurityConfig {

@Autowired
private DataSource dataSource;

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest().authenticated()
        .and()
        .formLogin(form -> form
            .loginPage("/login")
            .defaultSuccessUrl("/home", true)
            .permitAll()
        )
        .logout(logout -> logout.logoutUrl("/logout"));
    return http.build();

}

protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();       // encoder para criptografar os dados

     User.builder()
        .username("joao")
        .password(encoder.encode("joao"))
        .roles("ADM")
        .build();

    auth.jdbcAuthentication()
        .dataSource(dataSource)
        .passwordEncoder(encoder);
}

}

1 resposta

Para mim funcionou assim

@Configuration
@EnableWebSecurity
public class WebSecurityConfig{

    @Autowired
    private DataSource dataSource;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{

        http
            .authorizeHttpRequests()
                .anyRequest().authenticated()
            .and()
                .formLogin(form -> form
                    .loginPage("/login")
                    .defaultSuccessUrl("/home",true)
                    .permitAll())
                .logout(logout -> logout.logoutUrl("/logout"));

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public JdbcUserDetailsManager users(PasswordEncoder encoder){
        UserDetails user = 
                        User.builder()
                            .username("joao")
                            .password(encoder.encode("joao"))
                            .roles("ADM")
                            .build();
        JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager(dataSource);
        jdbcUserDetailsManager.createUser(user);
        return jdbcUserDetailsManager;
    }

}