首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Spring Security中添加PasswordEncoder到JdbcUserDetailsManager中?

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

Stack Overflow用户
提问于 2019-07-27 18:15:05
回答 1查看 202关注 0票数 0

我正在学习Spring Security,我想在JdbcUserDetailsManager上添加BCryptPasswordEncoder。

代码如下:

代码语言:javascript
运行
复制
@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注入到其他类中。谢谢!

EN

回答 1

Stack Overflow用户

发布于 2019-07-27 18:34:32

您应该使用此类创建UserDetails Bean

代码语言:javascript
运行
复制
@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;
}

}

在创建这个类之后,您将把这两个方法添加到

代码语言:javascript
运行
复制
@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());

}

代码语言:javascript
运行
复制
@Bean
public DaoAuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
    authenticationProvider.setUserDetailsService(userDetailsService);
    authenticationProvider.setPasswordEncoder(passwordEncoder());
    return authenticationProvider;
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57231145

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档