当前位置:网站首页>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,"退出成功");
}
}
边栏推荐
猜你喜欢
随机推荐
NLP commonly used Backbone model cheat sheet (1)
剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
pytest-常用运行参数
线上交流丨稀疏神经网络:实践和理论(青源Talk第23期 汪张扬)
【飞控开发高级教程1】疯壳·开源编队无人机-飞控整机代码走读、编译与烧写
npm运行项目dependencies were not found: core-js/modules/es6.array.fill
浅谈I2C知识
TensorFlow学习记录(一):基本介绍
2022年8月2日——使用idea搭建servlet+jsp项目
鲲鹏devkit开发套件
js显示隐藏手机号
matlab常微分方程在传染病建模中的应用
7.31
NVM和NRM
几种常见的跨域解决方法
并查集总结
心电记录电路设计(框图/波形以及信号放大器的选择)
【Autosar RTM】
[NCTF2019]SQLi-1||SQL注入
236. 二叉树的最近公共祖先