用户登录SpringSecurity查库实现
security包下新建MyUserDetailServiceImpl
bash
@Service
public class MyUserDetailServiceImpl implements UserDetailsService {
@Autowired
SysUserService sysUserService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
SysUser sysUser = sysUserService.getByUsername(username);
if(sysUser==null){
throw new UsernameNotFoundException("用户名或者密码错误!");
}else if("1".equals(sysUser.getStatus())){
throw new UserCountLockException("该用户账号已被封禁,具体联系管理员!");
}
return new User(sysUser.getUsername(),sysUser.getPassword(),getUserAuthority(sysUser.getId()));
}
private List<GrantedAuthority> getUserAuthority(Long id) {
return new ArrayList<>();
}
}
getByUsername实现:
bash
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
implements SysUserService{
@Override
public SysUser getByUsername(String username) {
return getOne(new QueryWrapper<SysUser>().eq("username",username));
}
}
SecurityConfig配置类里面配置下MyUserDetailServiceImpl
配置下默认加密bean
bash
@Bean
BCryptPasswordEncoder bCryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
自定义异常UserCountLockException
bash
public class UserCountLockException extends AuthenticationException {
public UserCountLockException(String msg, Throwable t) {
super(msg, t);
}
public UserCountLockException(String msg) {
super(msg);
}
}
全局异常GlobalExceptionHandler:
bash
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = RuntimeException.class)
public R handler(RuntimeException e){
log.error("运行时异常:----------------{}", e.getMessage());
System.out.println("运行时异常:");
return R.error(e.getMessage());
}
}