add:实现双token功能

master
msb_89821 2 years ago
parent 6bf989327b
commit 19fa8a7ddd

@ -4,10 +4,16 @@ public class PassengerConsonant {
public static final String phoneNumberCodePreKey = "smsCode_";
public static final String phoneNumberTokenPreKey = "tokenPre_";
// public static final String phoneNumberTokenPreKey = "tokenPre_";
//
// public static final String phoneNumberReshTokenPreKey = "reshTokenPre_";
public static final String PassengerIdendity = "1";
public static final String DriverIdendity = "2";
public static final String ACCESS_TOKEN_TYPE = "accessTokenType";
public static final String REFLSH_TOKEN_TYPE = "refshTokenType";
}

@ -6,6 +6,7 @@ import com.mashibing.dto.PassengerRequestDto;
import com.mashibing.dto.ResponseResult;
import com.mashibing.exception.BizExecption;
import com.mashibing.util.JwtUtils;
import com.mashibing.util.RediesPreKeyUtil;
import lombok.extern.slf4j.Slf4j;
import mashibing.online.text.consonant.PassengerConsonant;
import mashibing.online.text.dto.UserInfo;
@ -88,13 +89,23 @@ public class PassengerController {
passengerUserService.reginsterUserbyPhone(passengerRequestDto);
log.info("手机号码={} 完成注册!",phone);
// 返回token
String token = JwtUtils.genaroteToken(phone, PassengerConsonant.PassengerIdendity);
String accessToken = JwtUtils.genaroteToken(phone, PassengerConsonant.PassengerIdendity,PassengerConsonant.ACCESS_TOKEN_TYPE);
String refshToken = JwtUtils.genaroteToken(phone, PassengerConsonant.PassengerIdendity,PassengerConsonant.REFLSH_TOKEN_TYPE);
UserInfo userInfo =new UserInfo();
userInfo.setPhoneNumber(phone);
userInfo.setToken(token);
stringRedisTemplate.opsForValue().set(PassengerConsonant.phoneNumberTokenPreKey + phone+PassengerConsonant.PassengerIdendity,
token,2,TimeUnit.HOURS);
userInfo.setAccessToken(accessToken);
userInfo.setRefshToken(refshToken);
String accessTokenKey= RediesPreKeyUtil.generateKeyPre(PassengerConsonant.ACCESS_TOKEN_TYPE,phone,PassengerConsonant.PassengerIdendity);
String reshTokenKey= RediesPreKeyUtil.generateKeyPre(PassengerConsonant.REFLSH_TOKEN_TYPE,phone,PassengerConsonant.PassengerIdendity);
stringRedisTemplate.opsForValue().set(accessTokenKey,
accessToken,15,TimeUnit.SECONDS);
stringRedisTemplate.opsForValue().set(reshTokenKey,
refshToken,55,TimeUnit.SECONDS);
log.info("reshTokenKey ={},refshToken={}",reshTokenKey,refshToken);
return ResponseResult.success(userInfo);
}
}

@ -0,0 +1,81 @@
package mashibing.online.text.controller;
import cn.hutool.core.util.ObjectUtil;
import com.mashibing.dto.ResponseResult;
import com.mashibing.dto.TokenResult;
import com.mashibing.util.JwtUtils;
import com.mashibing.util.RediesPreKeyUtil;
import lombok.extern.slf4j.Slf4j;
import mashibing.online.text.consonant.PassengerConsonant;
import mashibing.online.text.dto.TokenQequstVo;
import mashibing.online.text.dto.UserInfo;
import mashibing.online.text.utils.BussizParaTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
* Copyright© 2020.10.20 by .All rights reserved.
* 1.
* 2.
* 3.使.
* <b>Description:</b><br>
*
* @author nod
* <b>ProjectName:</b> onelinetextplublic
* <br><b>PackageName:</b> mashibing.online.text.controller
* <br><b>ClassName:</b>
* <br><b>Date:</b> 2022/10/20 15:36
*/
@Slf4j
@RestController
public class TokenController {
@Resource
private StringRedisTemplate stringRedisTemplate;
@PostMapping("/parsetReshToken")
public ResponseResult parsetReshToken(@RequestBody TokenQequstVo tokenQequstVo){
if(ObjectUtil.isNull(tokenQequstVo) || ObjectUtil.isEmpty(tokenQequstVo.getReshToken())){
return ResponseResult.fail(1002,"reshToken 不能为空");
}
TokenResult tokenResult = BussizParaTokenUtil.pareToken(tokenQequstVo.getReshToken());
if(ObjectUtil.isNull(tokenResult)){
log.error("解析 reshToken 异常");
return ResponseResult.fail(1003,"解析 reshToken 异常");
}
String tokenType=tokenResult.getTokenType();
String phoneNum = tokenResult.getPhoneNum();
String idendity = tokenResult.getIdendity();
String reshTokenRedisKey= RediesPreKeyUtil.generateKeyPre(tokenType,phoneNum,idendity);
String redisToken = stringRedisTemplate.opsForValue().get(reshTokenRedisKey);
log.info("reshTokenKey ={},refshToken={}",reshTokenRedisKey,redisToken);
if(StringUtils.isBlank(redisToken) || !tokenQequstVo.getReshToken().equals(redisToken)){
return ResponseResult.fail(1005,"reshToken 无效");
}
log.info("解析 reshToken 成功!");
String accessToken = JwtUtils.genaroteToken(phoneNum, PassengerConsonant.PassengerIdendity,PassengerConsonant.ACCESS_TOKEN_TYPE);
String refshToken = JwtUtils.genaroteToken(phoneNum, PassengerConsonant.PassengerIdendity,PassengerConsonant.REFLSH_TOKEN_TYPE);
UserInfo userInfo =new UserInfo();
userInfo.setPhoneNumber(phoneNum);
userInfo.setAccessToken(accessToken);
userInfo.setRefshToken(refshToken);
String accessTokenKey= RediesPreKeyUtil.generateKeyPre(PassengerConsonant.ACCESS_TOKEN_TYPE,phoneNum,PassengerConsonant.PassengerIdendity);
stringRedisTemplate.opsForValue().set(accessTokenKey,
accessToken,15, TimeUnit.SECONDS);
stringRedisTemplate.opsForValue().set(reshTokenRedisKey,
refshToken,55,TimeUnit.SECONDS);
return ResponseResult.success(userInfo);
}
}

@ -0,0 +1,23 @@
package mashibing.online.text.dto;
import lombok.Data;
/**
* Copyright© 2020.10.20 by .All rights reserved.
* 1.
* 2.
* 3.使.
* <b>Description:</b><br>
*
* @author nod
* <b>ProjectName:</b> onelinetextplublic
* <br><b>PackageName:</b> mashibing.online.text.dto
* <br><b>ClassName:</b>
* <br><b>Date:</b> 2022/10/20 15:40
*/
@Data
public class TokenQequstVo {
private String reshToken;
}

@ -7,5 +7,7 @@ public class UserInfo {
private String phoneNumber;
private String token;
private String accessToken;
private String refshToken;
}

@ -32,6 +32,7 @@ public class InterceptorConfinger implements WebMvcConfigurer {
registry.addInterceptor(jwtIntercept()).addPathPatterns("/**")
.excludePathPatterns("/passenger/checkPhoneNumberCode")
.excludePathPatterns("/passenger/getPhoneNumberCode")
.excludePathPatterns("/parsetReshToken")
.excludePathPatterns("/test/noTokenTest");
}

@ -1,14 +1,11 @@
package mashibing.online.text.intercept;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.mashibing.constant.CommonStatusEnum;
import com.mashibing.dto.PassengerRequestDto;
import com.mashibing.dto.ResponseResult;
import com.mashibing.dto.TokenResult;
import com.mashibing.util.JwtUtils;
import javafx.print.Printer;
import lombok.extern.slf4j.Slf4j;
import mashibing.online.text.consonant.PassengerConsonant;
import mashibing.online.text.utils.BussizParaTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
@ -26,43 +23,30 @@ public class JwtIntercept implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info(" 进入拦截器 JwtIntercept === preHandle 方法");
String token = request.getHeader("Authorization");
String message=null;
boolean result =true;
TokenResult tokenResult =null;
if(StringUtils.isBlank(token)){
PrintWriter out = response.getWriter();
out.println(JSON.toJSONString(ResponseResult.fail(99, "token is empty !")));
return false;
}
try{
tokenResult = JwtUtils.parseToken(token);
}catch (Exception e){
log.error("解析token异常 e ={}",e.getCause());
message="parse token exception";
result =false;
}
if(result){
boolean result =false;
TokenResult tokenResult = BussizParaTokenUtil.pareToken(token);
if(ObjectUtil.isNotNull(tokenResult)){
String phone=tokenResult.getPhoneNum();
String idendity=tokenResult.getIdendity();
String tokenType = tokenResult.getTokenType();
//根据手机号 和身份类型 查询
String s = stringRedisTemplate.opsForValue().get(PassengerConsonant.phoneNumberTokenPreKey + phone + idendity);
if(StringUtils.isBlank(s)){
String s = stringRedisTemplate.opsForValue().get(tokenType + phone + idendity);
if(StringUtils.isBlank(s) || !token.equals(s)){
//token 无效
message="token not exist";
result =false;
}else{
// 比对token
if(!token.equals(s)){
message="token is inval";
result =false;
}else {
result = true;
}
}
}
if(!result){
PrintWriter out = response.getWriter();
out.println(JSON.toJSONString(ResponseResult.fail(99, message)));
out.println(JSON.toJSONString(ResponseResult.fail(99, "token is inval")));
}

@ -0,0 +1,43 @@
package mashibing.online.text.utils;
import com.alibaba.fastjson.JSON;
import com.mashibing.dto.ResponseResult;
import com.mashibing.dto.TokenResult;
import com.mashibing.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.PrintWriter;
/**
* Copyright© 2020.10.20 by .All rights reserved.
* 1.
* 2.
* 3.使.
* <b>Description:</b><br>
*
* @author nod
* <b>ProjectName:</b> onelinetextplublic
* <br><b>PackageName:</b> mashibing.online.text.utils
* <br><b>ClassName:</b>
* <br><b>Date:</b> 2022/10/20 11:39
*/
@Slf4j
public class BussizParaTokenUtil {
public static TokenResult pareToken(String token){
TokenResult tokenResult =null;
if(StringUtils.isBlank(token)){
log.error("token 为空");
return tokenResult;
}
try{
tokenResult = JwtUtils.parseToken(token);
}catch (Exception e){
log.error("解析token异常 e ={}",e.getCause());
tokenResult=null;
}
return tokenResult;
}
}

@ -18,5 +18,8 @@ import lombok.Data;
@Data
public class TokenResult {
private String phoneNum;
private String idendity;
private String tokenType;
}

@ -31,17 +31,20 @@ public class JwtUtils {
private static final String JWT_KEY = "phoneNum";
private static final String IDENDITY = "idendity";
private static final String TOKEN_TYPE = "tokenType";
private static final String TOKEN_TIME = "tokenTime";
//生成token
public static String genaroteToken(String phoneNum,String idendity){
public static String genaroteToken(String phoneNum,String idendity,String tokenType){
Map<String,String> map =new HashMap<>();
map.put(JWT_KEY,phoneNum);
map.put(IDENDITY,idendity);
map.put(TOKEN_TYPE,tokenType);
// Calendar calendar=Calendar.getInstance();
// calendar.add(Calendar.DATE,1);
// Date date =calendar.getTime();
Calendar calendar=Calendar.getInstance();
map.put(TOKEN_TIME,String.valueOf(calendar.getTimeInMillis()));
JWTCreator.Builder builder = JWT.create();
//遍历map,把map 的逐个元素值放到 builder里面去
@ -65,9 +68,11 @@ public class JwtUtils {
DecodedJWT verify = JWT.require(Algorithm.HMAC256(SINGN)).build().verify(token);
Claim phoneClaim = verify.getClaim(JWT_KEY);
Claim idendityClaim = verify.getClaim(IDENDITY);
Claim tokenType = verify.getClaim(TOKEN_TYPE);
TokenResult tokenResult = new TokenResult();
tokenResult.setIdendity(idendityClaim.asString());
tokenResult.setPhoneNum(phoneClaim.asString());
tokenResult.setTokenType(tokenType.asString());
return tokenResult;
}

@ -0,0 +1,21 @@
package com.mashibing.util;
/**
* Copyright© 2020.10.20 by .All rights reserved.
* 1.
* 2.
* 3.使.
* <b>Description:</b><br>
*
* @author nod
* <b>ProjectName:</b> onelinetextplublic
* <br><b>PackageName:</b> com.mashibing.util
* <br><b>ClassName:</b>
* <br><b>Date:</b> 2022/10/20 10:29
*/
public class RediesPreKeyUtil {
public static String generateKeyPre(String tokenType,String phone,String idendityType){
return tokenType+"_"+phone+"_"+idendityType;
}
}
Loading…
Cancel
Save