如何在Spring Security中将PasswordEncoder添加到JdbcUserDetailsManager中?

ogq8wdun  于 11个月前  发布在  Spring
关注(0)|答案(2)|浏览(210)

我正在学习Spring Security,我想在JdbcUserDetailsManager中添加BCryptPasswordEncoder。
这就是代码:

@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");
    }

}

字符串
我需要UserDetailsManager bean注入到其他类中。谢谢!

g0czyy6m

g0czyy6m1#

  • 我想在JdbcUserDetailsManager中添加BCryptPasswordEncoder。*

密码编码器属于DaoAuthenticationProvider,**不属于UserDetailsService。**当您使用JdbcUserDetailsManager设置新用户的密码时,您给予给JdbcUserDetailsManager的密码应该是 * 已加密的 *。
于是:

  • 你可以简单地将编码器声明为bean(我建议使用PasswordEncoderFactories.createDelegatingPasswordEncoder());
  • 它将在验证用户时自动使用-您只需配置您的UserDetailService
  • 当创建新用户时,需要在保存用户之前手动编码密码。所以你可以在你为此使用的服务类中完成,在那里注入你的编码器。

你通常不需要配置DaoAuthenticationProvider,但是如果你想配置,下面的代码就可以了:

@Bean
public AuthenticationManager authenticationManager (
UserDetailsService userDetailsService ,
PasswordEncoder encoder ) throws Exception {
  DaoAuthenticationProvider provider = new DaoAuthenticationProvider ();
  provider.setUserDetailsService(userDetailsService);
  provider.setPasswordEncoder(encoder);
  return new ProviderManager(provider);
}

字符串

umuewwlo

umuewwlo2#

您应该使用此类创建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;
}

字符串
}
创建该类后,您将在

@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());

}


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

相关问题