SpringSecurity使用UserDetailsService 接口来获取用户信息UserDetails ,根据UserDetails 的 getPassword() 方法,判断用户名密码是否正确。大致流程如下:
框架默认情况使用InMemoryUserDetailsManager ,即把用户信息存到内存里,一般在开发阶段使用。通过以下配置添加默认测试用户:
spring:
security:
user:
name: "user"
password: "123"
要使用自己的用户数据源,有三个地方要改,也就是上图标绿的部分:
自定义UserDetailsService替换掉 InMemoryUserDetailsManager,实现UserDetails loadUserByUsername(String username)方法。
如果要额外保存用户信息,例如手机号、生日等,就自定义UserDetails 在loadUserByUsername 中返回。
提供一个PasswordEncoder Bean。
InMemoryUserDetailsManager 初始化的位置是在UserDetailsServiceAutoConfiguration 配置文件里。这个配置有一些生效条件:
@ConditionalOnMissingBean(
value = { AuthenticationManager.class, AuthenticationProvider.class, UserDetailsService.class,
AuthenticationManagerResolver.class },
...
public class UserDetailsServiceAutoConfiguration {
@Bean
public InMemoryUserDetailsManager inMemoryUserDetailsManager(SecurityProperties properties,
ObjectProvider passwordEncoder) {
SecurityProperties.User user = properties.getUser();
List roles = user.getRoles();
return new InMemoryUserDetailsManager(User.withUsername(user.getName())
.password(getOrDeducePassword(user, passwordEncoder.getIfAvailable()))
.roles(StringUtils.toStringArray(roles))
.build());
}
}
所以,我们提供UserDetailsService Bean之后,配置就会自动失效。这是实例,要注意接口约定loadUserByUsername方法不能返回null,所以找不到用户时要抛UsernameNotFoundException 异常。
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
UserRepository repository;
/**
* Returns: a fully populated user record (never null)
* Throws: UsernameNotFoundException – if the user could not be found or the user has no GrantedAuthority
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional userOptional = repository.findOne((root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get("username"), username));
if (userOptional.isEmpty()) {
throw new UsernameNotFoundException(username);
}
User user = userOptional.get();
return new CustomUser(user.getUsername(), user.getPassword(), List.of());
}
}
UserDetails 用来存放身份认证和权限认证的信息,也可以额外存我们需要的信息。我这里直接继承SpringSecurity自带给JDBC用的User类型。
public class CustomUser extends User {
public DoitUser(String username, String password, Collection extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
public DoitUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection extends GrantedAuthority> authorities) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
}
}
由于DaoAuthenticationProvider 使用PasswordEncoder 对用户密码进行校验。
if (!this.passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
this.logger.debug("Failed to authenticate since password does not match stored value");
throw new BadCredentialsException(this.messages
.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
}
所以我们要提供一个PasswordEncoder 实现,可以用BCryptPasswordEncoder 。
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
另外,使用PasswordEncoder 别忘了在用户注册的时候,把用户密码先加密再保存!
public User register(@RequestBody User user) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
...
}