SpringBoot下token短信验证登入登出权限操作(token存放redis,ali短信接口)
SpringBoot下token短信验证登入登出(token存放redis)
不对SpringBoot进行介绍,具体的可以参考官方文档
介绍:token基本使用,redis基本使用
思路:获取短信(验证并限制发送次数,将code存放redis)-->登入(验证并限制错误次数,将用户信息及权限放token,token放redis)-->查询操作(略),主要将前两点,不足的希望指出,谢谢
步骤:
1.整合Redis需要的依赖,yml自行配置,ali短信接口依赖(使用引入外部包的方式)
org.springframework.boot spring-boot-starter-data-redis ....... ali taobao-sdk-java-auto system ${project.basedir}/libs/taobao-sdk-java-auto.jar org.springframework.boot spring-boot-maven-plugin org.springframework.boot spring-boot-maven-plugin true
2.ali短信接口工具类,发送验证码
@Autowired privateStringRedisTemplateredisTemplate; ....略.... //查询是否有此用户,记录单位时间内发送短信次数,并限制发送次数 Accountaccount=accountService.findByUserName(phone); if(account==null){ returnResultVOUtil.erro(0,"未注册用户"); } ValueOperationsops=redisTemplate.opsForValue(); StringgetTimes=ops.get(account+"code"); Integergts=getTimes==null?0:Integer.valueOf(getTimes); if(gts>5){ returnResultVOUtil.erro(0,"获取短信次数过多,请稍后再试"); } ops.set(account+"code",String.valueOf(gts+1),5,TimeUnit.MINUTES); NoteUtilsnoteUtils=newNoteUtils(); StringvalidCode=UidUtil.getValidCode();//生成随机数 try{ Stringyzmcode=noteUtils.yzmcode(validCode,phone); //redis设置验证码有效时间5分组 ops.set(phone,validCode,5,TimeUnit.MINUTES); }catch(Exceptione){ thrownewYunExceptions(0,"获取验证码服务器bug"); } //短信接口工具类 publicclassNoteUtils{ //仅当示例:具体参考官方文档 publicStringurl="***************"; publicStringappkey="****************"; publicStringsecret="*********************"; publicStringyzmcode(Stringcode,Stringtelnum)throwsApiException,JSONException{ TaobaoClientclient=newDefaultTaobaoClient(url,appkey,secret); AlibabaAliqinFcSmsNumSendRequestreq=newAlibabaAliqinFcSmsNumSendRequest(); req.setExtend("extend"); req.setSmsType("normal"); req.setSmsFreeSignName("*************"); req.setSmsParamString("{code:'"+code+"'}"); req.setRecNum(telnum); req.setSmsTemplateCode("******************"); AlibabaAliqinFcSmsNumSendResponsersp=client.execute(req); return"true"; } }
3.登入验证,并将权限保存在token,以下有token工具类,可直接copy使用
publicResultVologin(Stringphone,Stringcode,HttpServletResponseresponse,HttpServletRequestrequest){ ValueOperationsops=redisTemplate.opsForValue(); Stringvalidcode=ops.get(phone); Stringouttimes=ops.get(phone+"wrong"); Integerots=outtimes==null?0:Integer.valueOf(outtimes); if(ots>5){ returnResultVOUtil.erro(0,"错误次数过多,请稍后再试"); } if(validcode!=null){ Stringvcode=validcode.toString(); if(code.equalsIgnoreCase(vcode)){ Accountaccount=accountService.findByUserName(phone); if(account!=null){ //记录登入信息,获取权限,字符串类型a,b,c,d Stringtoken=TokenUtils.tokenGet(phone,account.getDbids()); Logloginloglogin=newLoglogin(); loglogin.setActionid(200); loglogin.setUserip(request.getRemoteAddr()); loglogin.setUsername(phone); loglogin.setLogtime(Timestamp.valueOf(TimeUtil.getCurDate())); loglogin.setUserid(account.getUserId()); logloginService.save(loglogin); 设置token时效 ops.set(phone+"token",token,60,TimeUnit.MINUTES); returnResultVOUtil.success(token); }else{ returnResultVOUtil.erro(0,"没有此账户"); } }else{ ops.set(phone+"wrong",String.valueOf(ots+1),5,TimeUnit.MINUTES); returnResultVOUtil.erro(0,"验证码错误"); } }else{ returnResultVOUtil.erro(0,"请先获取验证码"); } } //token工具类 publicclassTokenUtils{ publicstaticStringtokenGet(Stringusername,Stringlimits){ Map map=newHashMap<>(); map.put("alg","HS256"); map.put("typ","JWT"); try{ Algorithmalgorithm=Algorithm.HMAC256("*******"); Stringtoken=JWT.create() .withHeader(map) /*设置载荷Payload*/ .withClaim("loginName",username) .withClaim("limits",limits) //设置过期时间-->间隔一定时间验证是否本人登入 .withExpiresAt(newDate(System.currentTimeMillis()+3600000*5)) .withIssuer("****")//签名是有谁生成例如服务器 .withSubject("*****")//签名的主题 .withAudience("*****")//签名的观众也可以理解谁接受签名的 /*签名Signature*/ .sign(algorithm); returntoken; }catch(Exceptione){ e.printStackTrace(); } returnnull; } publicstaticStringvalidToken(Stringtoken,Stringdbid){ try{ Algorithmalgorithm=Algorithm.HMAC256("*******"); JWTVerifierverifier=JWT.require(algorithm) .withIssuer("SERVICE") .build(); DecodedJWTjwt=verifier.verify(token); Stringsubject=jwt.getSubject(); List audience=jwt.getAudience(); Map claims=jwt.getClaims(); Claimlimits=claims.get("limits"); //验证操作权限,set长度改变说明权限不一致 Stringss=limits.asString(); String[]split=ss.split(","); Set set=newHashSet<>(Arrays.asList(split)); intsize=set.size(); set.add(dbid); if(set.size()!=size){ returnnull; }else{ Claimname=claims.get("loginName"); returnname.asString(); } }catch(Exceptione){ e.printStackTrace(); } returnnull; }
4.接下来都比较简单
4.1获取数据-->前端传参数,后台验证即可,
4.2退出的时候,清除redis里的token数据即可,
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。