第一步:创建SpringSecurity配置文件
@Configuration
public class SpringSecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
第二步:自定义UserDetailsService
@Service
public class MyUserDetailsService implements UserDetailsService {
@Resource
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if (!"zhangsan".equals(username)) {
throw new UsernameNotFoundException("指定名称的用户不存在");
}
String password = passwordEncoder.encode("1234");
User user = new User(username, password, AuthorityUtils.createAuthorityList());
return user;
}
}
第三步:启动项目测试