token置换
分类: Java 专栏: 爱旅行项目 标签: token置换
2023-02-28 16:02:37 270浏览
token置换,在保护期不允许置换
背景:旧的token快失效的时候,想换一个新的token继续使用。
1.controller层代码
@PostMapping("/api/retoken") public Dto retoken(HttpServletRequest request){ String agent=request.getHeader("user-agent"); String token = request.getHeader("token"); try { String newtoken= tokenService.retoken(agent,token); long setGenTime = System.currentTimeMillis(); long setExpTime = System.currentTimeMillis()+7200000; ItripTokenVO vo = new ItripTokenVO(); vo.setToken(newtoken); vo.setGenTime(setGenTime); vo.setExpTime(setExpTime); return DtoUtil.returnDataSuccess(vo); } catch (Exception e) { e.printStackTrace(); return DtoUtil.returnFail(e.getMessage(), ErrorCode.AUTH_UNKNOWN); } }
2.service层代码
public String retoken(String agent, String token) throws Exception { String userStr = redisAPI.get(token); if (!StringUtils.hasText(userStr)) { throw new Exception("token无效"); } //token的生成时间 Date genTime=null; //token:pc-usercode- String[] tokenDetails = token.split("-"); String genTimeStr = tokenDetails[3];//旧的token生成时间 SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyyMMddHHmmss"); genTime = simpleDateFormat.parse(genTimeStr); //token保护时间1小时 long passTime = System.currentTimeMillis()- genTime.getTime(); if(passTime<3600*1000){ throw new Exception("token还处在置换保护期,剩余"+(3600000-passTime)/1000 +"(s),禁止置换"); } //开始置换token ItripUser itripUser = JSON.parseObject(userStr, ItripUser.class); String newtoken = userService.createToken(itripUser, agent); if(UserAgentUtil.CheckAgent(agent)){//移动端是永久 redisAPI.set(newtoken,userStr); }else{ redisAPI.set(newtoken,userStr,7200); } //旧的token给个2分钟过渡时间 redisAPI.set(token,userStr,120);//2分钟后旧的token过期 return newtoken; }
好博客就要一起分享哦!分享海报
此处可发布评论
评论(0)展开评论
暂无评论,快来写一下吧
展开评论
他的专栏
他感兴趣的技术