From eed2d65b21bb4106479d1cb16d20e754b28e0b9c Mon Sep 17 00:00:00 2001 From: hgx Date: Sun, 24 Sep 2023 16:06:33 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BB=8Eredis=E4=B8=AD=E8=AF=BB=E5=8F=96token,?= =?UTF-8?q?=E5=B9=B6=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Service/VerificationCodeService.java | 21 +- .../interceptor/InterceptorConfig.java | 12 +- .../interceptor/JwtInterceptor.java | 36 +++- api-passenger/src/test/java/test/Test04.java | 1 - api-passenger/src/test/java/test/Test05.java | 200 ++++++++++++++++++ .../Service/VerificationCodeService.class | Bin 5011 -> 4995 bytes .../internal/common/util/JwtUtils.java | 6 +- .../common/util/RedisPrefixUtils.java | 28 +++ .../internal/common/util/JwtUtils.class | Bin 4396 -> 4359 bytes 9 files changed, 285 insertions(+), 19 deletions(-) create mode 100644 api-passenger/src/test/java/test/Test05.java create mode 100644 internal-common/src/main/java/com/mashibing/internal/common/util/RedisPrefixUtils.java diff --git a/api-passenger/src/main/java/com/mashibing/apipassenger/Service/VerificationCodeService.java b/api-passenger/src/main/java/com/mashibing/apipassenger/Service/VerificationCodeService.java index 1f501e0..c2cecf4 100644 --- a/api-passenger/src/main/java/com/mashibing/apipassenger/Service/VerificationCodeService.java +++ b/api-passenger/src/main/java/com/mashibing/apipassenger/Service/VerificationCodeService.java @@ -9,6 +9,7 @@ import com.mashibing.internal.common.request.VerificationCodeDTO; import com.mashibing.internal.common.response.NumberCodeResponse; import com.mashibing.internal.common.response.TokenResponse; import com.mashibing.internal.common.util.JwtUtils; +import com.mashibing.internal.common.util.RedisPrefixUtils; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -23,8 +24,7 @@ public class VerificationCodeService { @Autowired private ServiceVerificationCodeClient serviceVerificationCodeClient; - //乘客验证码的前缀 - private String verificationCodePrefix = "passenger-verification-code-"; + @Autowired private StringRedisTemplate stringRedisTemplate; @@ -49,7 +49,7 @@ public class VerificationCodeService { System.out.println("存入redis"); //key,value,过期时间 - String key = generatorKeyByPhone(passengerPhone); + String key = RedisPrefixUtils.generatorKeyByPhone(passengerPhone); stringRedisTemplate.opsForValue().set(key,numberCode+"",2, TimeUnit.MINUTES); @@ -58,14 +58,6 @@ public class VerificationCodeService { return ResponseResult.success(); } - /** - * 根据手机号生成key - * @param passengerPhone - * @return - */ - private String generatorKeyByPhone(String passengerPhone){ - return verificationCodePrefix+passengerPhone; - } @Autowired private ServicePassengerUserClient servicePassengerUserClient; @@ -82,7 +74,7 @@ public class VerificationCodeService { System.out.println("根据手机号,去redis读取验证码"); //生成key - String key = generatorKeyByPhone(passengerPhone); + String key = RedisPrefixUtils.generatorKeyByPhone(passengerPhone); //根据key获取value String codeRedis = stringRedisTemplate.opsForValue().get(key); @@ -107,6 +99,11 @@ public class VerificationCodeService { // 颁发令牌,不应用魔法值,用常量 String token = JwtUtils.generatorToken(passengerPhone, IdentityConstant.PASSENGER_IDENTITY); + //将token存储到redis + String tokenKey = RedisPrefixUtils.generatorTokenKey(passengerPhone,IdentityConstant.PASSENGER_IDENTITY); + stringRedisTemplate.opsForValue().set(tokenKey,token,30,TimeUnit.DAYS); + + //响应 TokenResponse tokenResponse = new TokenResponse(); tokenResponse.setToken(token); diff --git a/api-passenger/src/main/java/com/mashibing/apipassenger/interceptor/InterceptorConfig.java b/api-passenger/src/main/java/com/mashibing/apipassenger/interceptor/InterceptorConfig.java index 4da951e..aa7e71b 100644 --- a/api-passenger/src/main/java/com/mashibing/apipassenger/interceptor/InterceptorConfig.java +++ b/api-passenger/src/main/java/com/mashibing/apipassenger/interceptor/InterceptorConfig.java @@ -1,16 +1,24 @@ package com.mashibing.apipassenger.interceptor; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class InterceptorConfig implements WebMvcConfigurer { + + @Bean + public JwtInterceptor jwtInterceptor(){ + return new JwtInterceptor(); + } @Override public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(new JwtInterceptor()) + registry.addInterceptor(jwtInterceptor()) // 拦截的路径 .addPathPatterns("/**") // 不拦截的路径 - .excludePathPatterns("/noAuthTest"); + .excludePathPatterns("/noAuthTest") + .excludePathPatterns("/verification-code") + .excludePathPatterns("/verification-code-check"); } } diff --git a/api-passenger/src/main/java/com/mashibing/apipassenger/interceptor/JwtInterceptor.java b/api-passenger/src/main/java/com/mashibing/apipassenger/interceptor/JwtInterceptor.java index 8ff963e..7c98a21 100644 --- a/api-passenger/src/main/java/com/mashibing/apipassenger/interceptor/JwtInterceptor.java +++ b/api-passenger/src/main/java/com/mashibing/apipassenger/interceptor/JwtInterceptor.java @@ -4,8 +4,13 @@ import com.auth0.jwt.exceptions.AlgorithmMismatchException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.exceptions.TokenExpiredException; import com.mashibing.internal.common.dto.ResponseResult; +import com.mashibing.internal.common.dto.TokenResult; import com.mashibing.internal.common.util.JwtUtils; +import com.mashibing.internal.common.util.RedisPrefixUtils; import net.sf.json.JSONObject; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; @@ -14,6 +19,9 @@ import java.io.PrintWriter; public class JwtInterceptor implements HandlerInterceptor { + @Autowired + private StringRedisTemplate stringRedisTemplate; + @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { @@ -21,9 +29,10 @@ public class JwtInterceptor implements HandlerInterceptor { String resultString = ""; String token = request.getHeader("Authorization"); + TokenResult tokenResult = null; try { - JwtUtils.parseToken(token); + tokenResult = JwtUtils.parseToken(token); }catch(SignatureVerificationException e){ resultString = "token sign error"; result = false; @@ -38,6 +47,31 @@ public class JwtInterceptor implements HandlerInterceptor { result = false; } + if(tokenResult == null){ + resultString = "token invalid"; + result = false; + }else { + + + String phone = tokenResult.getPhone(); + String identity = tokenResult.getIdentity(); + + String tokenKey = RedisPrefixUtils.generatorTokenKey(phone,identity); + // 从redis 中取出token + String tokenRedis = stringRedisTemplate.opsForValue().get(tokenKey); + if(StringUtils.isBlank(tokenRedis)){ + resultString = "token invalid"; + result = false; + }else{ + if(!token.trim().equals(tokenRedis.trim())){ + resultString = "token invalid"; + result = false; + } + } + + } + // 比较我们传入的token和redis中token是否相等 + if(!result){ PrintWriter out = response.getWriter(); out.println(JSONObject.fromObject(ResponseResult.fail(resultString)).toString()); diff --git a/api-passenger/src/test/java/test/Test04.java b/api-passenger/src/test/java/test/Test04.java index ef24680..23b929d 100644 --- a/api-passenger/src/test/java/test/Test04.java +++ b/api-passenger/src/test/java/test/Test04.java @@ -4,7 +4,6 @@ import org.junit.Test; import java.util.Hashtable; import java.util.Map; -import java.util.TreeMap; public class Test04 { diff --git a/api-passenger/src/test/java/test/Test05.java b/api-passenger/src/test/java/test/Test05.java new file mode 100644 index 0000000..319e33b --- /dev/null +++ b/api-passenger/src/test/java/test/Test05.java @@ -0,0 +1,200 @@ +package test; + +import org.junit.Test; + +public class Test05 { + + @Test + public void test01() { + int testTimes = 100000000; + int count = 0; + for (int i = 0; i < testTimes; i++){ + if(Math.random()<0.3){ + count++; + } + } + System.out.println((double)count/ (double)testTimes); + } + + @Test + public void test02() { + int testTimes = 100000000; + int count = 0; + for (int i = 0; i < testTimes; i++){ + if(Math.random() *8< 5){ + count++; + } + } + System.out.println((double)count/ (double)testTimes); + } + + @Test + public void test03(){ + int k=9; + int testTimes = 100000000; + int count = 0; + int[] counts = new int[k]; + for (int i = 0; i < testTimes; i++){ + int ans = (int)(Math.random()*k); + counts[ans]++; + } + for(int i=0;iarr[i]){ + return false; + } + max = Math.max(max,arr[i]); + } + return true; + } + + @Test + public void test09(){ + int maxLen =50; + int maxValue = 1000; + } +} diff --git a/api-passenger/target/classes/com/mashibing/apipassenger/Service/VerificationCodeService.class b/api-passenger/target/classes/com/mashibing/apipassenger/Service/VerificationCodeService.class index 65287c9f593de7626e77e2119003c671f78e98f5..d7250c81c48b7532588e9d8fd98262fa70cf2e23 100644 GIT binary patch delta 1531 zcmZXU`CC*~7{@<%X6~FjcMggJX%hmPDFrGRq&XU;*&^;+L|RHQ5=xkWrddv=WM#J9 z7MEPgY}atGVGvWYRacT`O%`cU%`A1gl5e9C8F|o#GqKw|r+Y&Kv3!cw3#qobNS1@T2A@BYvjaqC#v#q$TB@ar%dU zF|o(_)gtE2^5uDd`U*SBLT4K!4H_6fBW~NFtiMIUW7!=*AB)*70MWFaF zc6P9fppO|NQ>Y%C6roBncjMM{5{~E;S@|jYrRXpIk?dH>sNt#H^mJB&5a-()% zfbor7Bta6;FPDKyF76^4B+Vt>U)jZpD#o%>$S_DNd%*}&15{v9#WVq&OD)rxA)pJn zg_+C}3MUGMv&9+^pAzQC&StK}m~MOh=ZXJ((b$%_n7$WCaBtsxq)7bQNbOCqDvjE)5}YiUfKqf|wMxs)ZjGDBcD<&vQy z=0u%nFvV3-C(YP)Y08he0aZjY(h=UWgsDQ|XuMD`Nl2JVH8tEOPvgRbJTZ&ez!EkK z$sTp=q@I0Z>Y|Yo^1z&=DKnf!y^Nh7&gs742#b<#nlPIs{$>z30)l6vls(WHOV<3$%eoW1$7NLfYC^L2OV^aAy(00!0Ku8%nUYC9M?%4T50Z zl|co>1!Zw*m8OuUR1tT@eLH^fljrckKSGc9O)7^Ylbk#A-uFKDKKHrr%=QYmB7ORw z6DNVG{N`{q%{GYu(^wmzg>^PbhxOd6J*`3Rqs^h64vP&A4k?RH2c6F`T9@VQI7CUVov*~eooF@W2$y1J) zr?q)TM?ULN&U4y4Z?Vf^3eDQMy3Fn%FYuzpOE!BP_Oj37WrsQ)QOACbe#PQdi`NV$ zbS6^W$)>~-H(+Ec!`+Ega&59H-j!@`o73K$SeQzzO>Q&@&08Puj@Put+gfTCccqeT zEdx2@fHBbKH4XPKXO`RP`_o-*HX1wK6XuF4gYg~l&dx+zOCnW$ZqDi^Nm{L#!L=5z zD-Q66TjsASdsA_cLyGBKV{uqSInnL$mwJ!T>mK&kE$HJtMIY}g zj?!=7udA(-%OH5BZ_k+>hf;~=WT)aT8Wh(t(;}l7;Ftjx#}!!yEpmz>PAG=?z@2Pe z;r)=4Zlg6L`jO%kA6tB)_>|8SpVO=Of_}x9e5LqWKb_{A0;~EG#kZRGEUvfsPVqfI z7)%$wWp30i5B#Y3iJuLo<~!J8hl9W9=wW^}h`Ifq*ud}hAI8As;AWqDa!f;dnw&iF z;n6}MHDu+NdrTh{En5CAEuFU~1pepq$@&Ini=88=dcjNo1fzo((U9jj-u`^D8^t=Z z2_>X`lyZ|iszNL`bBnADZsj%!kvxV^`1r-woxv9}v-qROu!{Uc*dFFrWeJ?Z$r79? z+ry~FK}Ll}XBjggOHr0$i4TQhK8+o#v6X|2iA9j(N;J_-XBOCuFcn_hE-D#}V-0heC#=g^%6t~!6@QF7#QJ2Xl7;eQ za_305h4@7hzgRq`A!)Saa)b(v%i1G92oI+VeFJ_Jem*JV(NJzT4{FS0^}^a z@CdteY8WgLf(3CqgrqI7j21{lC4Wm<S zWB&9obrN%B%!*hMf0nBvR*tD!054jA*%XOgB%L%cnq^F+QG~xo{41sXRV+o+Wi zcgt+|i~cLb=a;mjguqI9{Z~m!h39XUTdbCUS$^IDkK{&@>Y2y$cFozBuL=GI6-y^Y diff --git a/internal-common/src/main/java/com/mashibing/internal/common/util/JwtUtils.java b/internal-common/src/main/java/com/mashibing/internal/common/util/JwtUtils.java index 710563e..2ef341c 100644 --- a/internal-common/src/main/java/com/mashibing/internal/common/util/JwtUtils.java +++ b/internal-common/src/main/java/com/mashibing/internal/common/util/JwtUtils.java @@ -35,7 +35,7 @@ public class JwtUtils { builder.withClaim(k,v); }); //整合过期时间 - builder.withExpiresAt(date); + //builder.withExpiresAt(date); String sign = builder.sign(Algorithm.HMAC256(SIGN)); return sign; @@ -44,8 +44,8 @@ public class JwtUtils { //解析token public static TokenResult parseToken(String token){ DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token); - String phone = verify.getClaim(JWT_KEY_PHONE).toString(); - String identity = verify.getClaim(JWT_KEY_IDENTITY).toString(); + String phone = verify.getClaim(JWT_KEY_PHONE).asString(); + String identity = verify.getClaim(JWT_KEY_IDENTITY).asString(); TokenResult tokenResult = new TokenResult(); tokenResult.setPhone(phone); diff --git a/internal-common/src/main/java/com/mashibing/internal/common/util/RedisPrefixUtils.java b/internal-common/src/main/java/com/mashibing/internal/common/util/RedisPrefixUtils.java new file mode 100644 index 0000000..216e45c --- /dev/null +++ b/internal-common/src/main/java/com/mashibing/internal/common/util/RedisPrefixUtils.java @@ -0,0 +1,28 @@ +package com.mashibing.internal.common.util; + +public class RedisPrefixUtils { + + //乘客验证码的前缀 + public static String verificationCodePrefix = "passenger-verification-code-"; + + //token存储的前缀 + public static String tokenPrefix = "token-"; + /** + * 根据手机号生成key + * @param passengerPhone + * @return + */ + public static String generatorKeyByPhone(String passengerPhone){ + return verificationCodePrefix+passengerPhone; + } + + /** + * 根据手机号和身份标识,生成token + * @param phone + * @param identity + * @return + */ + public static String generatorTokenKey(String phone,String identity){ + return tokenPrefix+phone + "-"+identity; + } +} diff --git a/internal-common/target/classes/com/mashibing/internal/common/util/JwtUtils.class b/internal-common/target/classes/com/mashibing/internal/common/util/JwtUtils.class index a64fd0d1d460e71977dc58006453d5cbeb236f0a..7f67f35e78851403e6f23c159a3f9a4c6be677e2 100644 GIT binary patch delta 1273 zcmYk6+jA3j6vscin`AeemBv+sMQqcw7D!4lZE2wuC{zoUwpJ0jX=}MxDJZS?O8_s3 zsC8!F93OqDpi(MnE`S#<54_+w!yAvvzzj3~2ae~r=|Gd&-`R8jp6~C>o=zT5X0QEM zya+UN!zRsu$)Js{G zH)FiT+cxj;ZjASMKgI`qX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