Search code examples
spring-bootspring-security

security configuration with spting boot


I am new at Spring Can someone explain to me the role of these two methods (loadUserByUsername and configure) ? I am trying to understand spring security

@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(myAuthenticationProvider);
    }
@Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        UserBuilder builder = null;
        User user = userRepository.findByEmail(email);
        if (user==null) {
            throw new UsernameNotFoundException(email);
        }else{
            builder = org.springframework.security.core.userdetails.User.withUsername(email);
            builder.password(user.getPassword());
            builder.roles(user.getRole());
        }
        return builder==null ? null : builder.build();
    }

}

Solution

  • The UserDetailsService bean is used by the DaoAuthenticationProvider to retrieve user information in order to authenticate them. It is a core interface inside Spring Security.

    The configure(AuthenticationManagerBuilder auth) method can be used to expose the resulting AuthenticationManager as a bean. You can do something like:

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
            auth
            // enable in memory based authentication with a user named
            // "user" and "admin"
            .inMemoryAuthentication().withUser("user").password("password").roles("USER").and()
                    .withUser("admin").password("password").roles("USER", "ADMIN");
    }
    

    Although, you can achieve the same as above by doing:

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

    Be aware that the WebSecurityConfigurerAdapter class has been deprecated in Spring Security 5.7.0-M2, thus not being recommended anymore. The blog post provide more detail on that.