1.自定义的用户信息类需要实现 org.springframework.security.core.userdetails.UserDetails 接口,并实现里面的方法,英语不好,转成中文注释,凑合看下吧
UserDetails 源码:
public interface UserDetails extends Serializable {
/**
* 权限列表,集合中的每个对象需要是GrantedAuthority的子类,很简单,
* 自己 new 一个 SimpleGrantedAuthority即可,
*
* @return the authorities, sorted by natural key (never <code>null</code>)
*/
Collection<? extends GrantedAuthority> getAuthorities();
/**
* 获取密码(数据库中加密后的密码)
*
* @return the password
*/
String getPassword();
/**
* 获取用户名
*
* @return the username (never <code>null</code>)
*/
String getUsername();
/**
* 帐户未过期
* @return <code>true</code> if the user's account is valid (ie non-expired),
* <code>false</code> if no longer valid (ie expired)
*/
boolean isAccountNonExpired();
/**
* 帐户未锁定
*
* @return <code>true</code> if the user is not locked, <code>false</code> otherwise
*/
boolean isAccountNonLocked();
/**
* 凭证未过期
*
* @return <code>true</code> if the user's credentials are valid (ie non-expired),
* <code>false</code> if no longer valid (ie expired)
*/
boolean isCredentialsNonExpired();
/**
* 已启用该用户
*
* @return <code>true</code> if the user is enabled, <code>false</code> otherwise
*/
boolean isEnabled();
}
2.判断密码是否通过 ,加密使用的类和解密使用的类需要是同一个
// passwordEncoder.matches:判断密码是否相同
// password :用户输入密码
// userDetails.getPassword():从数据库查询的密码
if(!passwordEncoder.matches(password,userDetails.getPassword())){
throw new BadCredentialsException("密码不正确");
}
3.设置上下文
// 我也不清楚这个是干嘛的。。。
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
// 将用户信息保存到上下文中
SecurityContextHolder.getContext().setAuthentication(authentication);
登录部分的代码(源码出自:https://github.com/macrozheng/mall-swarm)
public String login(String username, String password) {
String token = null;
//密码需要客户端加密后传递
try {
UserDetails userDetails = loadUserByUsername(username);
if(!passwordEncoder.matches(password,userDetails.getPassword())){
throw new BadCredentialsException("密码不正确");
}
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
token = jwtTokenUtil.generateToken(userDetails);
updateLoginTimeByUsername(username);
insertLoginLog(username);
} catch (AuthenticationException e) {
LOGGER.warn("登录异常:{}", e.getMessage());
}
return token;
}