简体   繁体   中英

How to add PasswordEncoder into JdbcUserDetailsManager in Spring Security?

I'm learning about Spring Security and I want to add the BCryptPasswordEncoder at the JdbcUserDetailsManager.

This is the code:

@Configuration
@EnableWebSecurity
public class DemoSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();
    }

    @Bean
    @Autowired
    public UserDetailsManager userDetailsManager(DataSource securityDataSource) {

        JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager();

        jdbcUserDetailsManager.setDataSource(securityDataSource);

        return jdbcUserDetailsManager; 
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()   
                .antMatchers("/").hasRole("EMPLOYEE")
                .antMatchers("/leaders/**").hasRole("MANAGER")
                .antMatchers("/systems/**").hasRole("ADMIN")
            .and()
            .formLogin() 
                .loginPage("/showMyLoginPage")  
                .loginProcessingUrl("/authenticateTheUser")  
                .permitAll()  
            .and()
            .logout().permitAll()  
            .and()
            .exceptionHandling().accessDeniedPage("/access-denied");
    }

}

I need the UserDetailsManager bean to inject in other class. Thank you!

You should use this class to create the UserDetails Bean

@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService{

static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);

@Autowired
private com.fortsolution.schedmate.data.services.UserService userService;

@Transactional(readOnly=true)
public UserDetails loadUserByUsername(String ssoId)
        throws UsernameNotFoundException {
    System.out.println("fine here murtaza");
    int id = Integer.parseInt(ssoId);
    User user = userService.findById(id);
    logger.info("User : {}", user);
    if(user==null){
        logger.info("User not found");
        throw new UsernameNotFoundException("Username not found");
    }
    return new org.springframework.security.core.userdetails.User(""+user.getId(), user.getPassword(), 
             true, true, true, true, getGrantedAuthorities(user));
}


private List<GrantedAuthority> getGrantedAuthorities(User user){
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

    for(UserProfile userProfile : user.getUserProfiles()){
        logger.info("UserProfile : {}", userProfile);
        authorities.add(new SimpleGrantedAuthority("ROLE_"+userProfile.getType()));

    }

    return authorities;
}

}

after creating this class you will add these two method in your

@Autowired
@Qualifier("customUserDetailsService")
UserDetailsService userDetailsService;

@Override
@Autowired // <-- This is crucial otherwise Spring Boot creates its own
protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    auth.userDetailsService(userDetailsService);
    auth.authenticationProvider(authenticationProvider());

}

and

@Bean
public DaoAuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
    authenticationProvider.setUserDetailsService(userDetailsService);
    authenticationProvider.setPasswordEncoder(passwordEncoder());
    return authenticationProvider;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM