接上篇token校验,现在实现一下退出登录的功能
Controller层
@PostMapping("/logout")
public Result logout(){
return LoginService.logout();
}
Service层
退出登录的本质就是要删除redis中缓存的用户信息,因为调接口就必须携带token,就会走认证过滤器的流程,如果redis中没有对应的用户信息,那么token就是无效的。
我们要获取userId,然后根据userId删除redis中的缓存,那么就用SecurityContextHolder来获取userId。 SecurityContextHolder底层是用ThreadLocal实现的,也就说明同一个线程里都可以访问到之前在过滤器里面存储到SecurityContextHolder里的用户对象。
@Override
public Result logout() {
//1、获取token,解析出userId
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
LoginUser loginUser = (LoginUser) authentication.getPrincipal(); //强转
Long userId = loginUser.getUser().getId();
//2、删除redis中缓存的用户信息
redisCache.deleteObject("login:"+userId);
return Result.okResult();
}