编写一个类自定义实现 UserDetailsService 接口
@Service("customUserDetailService")
public class CustomUserDetailService implements UserDetailsService { @Autowired
private UserRepository userRepository; @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { System.out.println("在 CustomUserDetailService 传入的 username => " + username); com.liwei.entity.User user = userRepository.findByUserName(username);
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
User securityUser = new User(user.getUserName(), user.getPassword(), authorities);
return securityUser;
}
}
指定装配 UserDetailsService
@Autowired
@Qualifier("customUserDetailService")
private UserDetailsService userDetailsService;
配置 userDetailsService
auth.userDetailsService(userDetailsService)
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(new PasswordEncoder() {
/**
* 这个方法的注释我不知道应该怎样写,含义是提供一个加密的算法?
*
* @param rawPassword
* @return
*/
@Override
public String encode(CharSequence rawPassword) {
return encoder.encode(rawPassword.toString());
} /**
* 提供一个匹配的算法
*
* @param rawPassword 用户输入的密码
* @param encodedPassword "数据库"中的密码,可以理解为安全数据源的密码
* @return
*/
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return encoder.matches(rawPassword, encodedPassword);
}
});
//.withUser("liwei").password("c019306df0757d86de9a14c1033fb80d84fa77f13edc4ff985dacac612043657a0246bd8e6b3ebab").roles("USER").and()
//.withUser("zhouguang").password("2f4353cc3b8bc0fbde0a6aad1a438dec110c3362b33e0804e95e6f3368e80625fdd5dd2aacdcdf32").roles("USER", "ADMIN");
}