当前位置:网站首页>12-security退出.md
12-security退出.md
2022-08-03 00:34:00 【张 邵】
我们只需要定义一个登出接口,然后获取SecurityContextHolder中的认证信息,删除redis中对应的数据即可。
/** * @Author 三更 B站: https://space.bilibili.com/663528522 */
@Service
public class LoginServiceImpl implements LoginServcie {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private RedisCache redisCache;
@Override
public ResponseResult login(User user) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
Authentication authenticate = authenticationManager.authenticate(authenticationToken);
if(Objects.isNull(authenticate)){
throw new RuntimeException("用户名或密码错误");
}
//使用userid生成token
LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
String userId = loginUser.getUser().getId().toString();
String jwt = JwtUtil.createJWT(userId);
//authenticate存入redis
redisCache.setCacheObject("login:"+userId,loginUser);
//把token响应给前端
HashMap<String,String> map = new HashMap<>();
map.put("token",jwt);
return new ResponseResult(200,"登陆成功",map);
}
@Override
public ResponseResult logout() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
LoginUser loginUser = (LoginUser) authentication.getPrincipal();
Long userid = loginUser.getUser().getId();
redisCache.deleteObject("login:"+userid);
return new ResponseResult(200,"退出成功");
}
}
边栏推荐
猜你喜欢
随机推荐
和睦家私有化后换帅:新风天域吴启楠任CEO 李碧菁靠边站
【深度学习】基于tensorflow的小型物体识别训练(数据集:CIFAR-10)
全栈---Proxy
接口流量突增,如何做好性能优化?
236. 二叉树的最近公共祖先
并查集总结
SAP 电商云 Spartacus UI 的持续集成 - Continous integration
Nacos配置中心之事件订阅
[NCTF2019]SQLi-1||SQL注入
投资的思考
增删改查这么多年,最后栽在MySQL的架构设计上!
写一个简单的网站步骤
Introduction to resubmit Progressive Anti-Duplicate Submission Framework
PAT甲级 1051 Pop Sequence
优秀论文以及思路分析01
全栈---CORS
剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
公司招个程序员,34岁以上两年一跳的不要,开出工资以为看错了
有奖提问|《新程序员》专访“Apache之父”Brian Behlendorf
Nuxt 所有页面都设置上SEO相关标签