Demo源码:https://github.com/ygsama/ipa
自定义登录认证的实现
需要实现三个接口
UserDetails 用户类接口
UserDetailsService 查询用户密码的service 接口
AuthenticationProvider 为认证管理器AuthenticationManager 提供验证组件AuthenticationProvider
/**
* 实现了 {@link UserDetails}接口
* 用于构建存储在SecurityContextHolder的Authentication对象
*
* @author ygsama
*/
@Slf4j
@Data
public class SysUserDO implements UserDetails {
private String username;
private String password;
private String name;
private List<SysRoleDO> roleList;
// ... 其他字段省略
/**
* 装填用户的角色列表
*/
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
if (roleList == null || roleList.size() < 1) {
return AuthorityUtils.commaSeparatedStringToAuthorityList("");
}
log.info("[原始用户角色列表装填]: ", roleList);
StringBuilder roles = new StringBuilder();
for (SysRoleDO role : roleList) {
roles.append("ROLE_").append(role.getNo()).append(",");
}
List<GrantedAuthority> authorityList = AuthorityUtils.commaSeparatedStringToAuthorityList(roles.substring(0, roles.length() - 1));
log.info("[遍历并返回用户的角色列表]: {}", authorityList);
return authorityList;
}
@Override
public String getPassword() {
return this.password;
}
@Override
public String getUsername() {
return this.username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
/**
* 用户登录的service实现类 <br>
* 框架的默认实现是{@link JdbcDaoImpl} <br>
*
* @author ygsama
*/
@Slf4j
@Service("userDetailsService")
public class LoginUserDetailsServiceImpl implements UserDetailsService {
private final AuthUserMapper authUserMapper;
private final AuthRoleMapper authRoleMapper;
@Autowired
public LoginUserDetailsServiceImpl(AuthUserMapper authUserMapper, AuthRoleMapper authRoleMapper) {
this.authUserMapper = authUserMapper;
this.authRoleMapper = authRoleMapper;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
SysUserDO sysUserDO = authUserMapper.selectByPrimaryKey(username)