From c87c7bb9932ce0c994ea560071e57511a0b49a34 Mon Sep 17 00:00:00 2001 From: yh <1844516659@qq.com> Date: Sat, 16 Jul 2022 23:58:17 +0800 Subject: [PATCH] =?UTF-8?q?=E9=A3=9E=E6=BB=B4=E5=87=BA=E8=A1=8C=E7=BD=91?= =?UTF-8?q?=E7=BA=A6=E8=BD=A62022-=E4=B9=98=E5=AE=A2=E6=9C=8D=E5=8A=A1=20r?= =?UTF-8?q?edis=E5=AD=98=E5=82=A8token=E5=B9=B6=E4=BD=BF=E7=94=A8=E6=8B=A6?= =?UTF-8?q?=E6=88=AA=E5=99=A8=E8=BF=9B=E8=A1=8C=E7=9A=84=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../interceptor/InterceptorConfig.java | 14 ++++- .../interceptor/JwtInterceptor.java | 60 +++++++++++++++++-- .../service/VerificationCodeService.java | 22 ++++--- .../internalcommon/util/JwtUtils.java | 31 ++++++---- 4 files changed, 98 insertions(+), 29 deletions(-) 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 dd92cbc..9834d68 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,5 +1,6 @@ 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; @@ -7,12 +8,21 @@ 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") + ,("/verification-code") + ,("/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 73f3a6c..676be08 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,12 @@ import com.auth0.jwt.exceptions.AlgorithmMismatchException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.exceptions.TokenExpiredException; import com.mashibing.internalcommon.dto.ResponseResult; +import com.mashibing.internalcommon.dto.TokenResult; import com.mashibing.internalcommon.util.JwtUtils; 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,15 +18,30 @@ import java.io.PrintWriter; public class JwtInterceptor implements HandlerInterceptor { + @Autowired + private StringRedisTemplate redisTemplate; + @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + // 返回 结果是否通过 boolean result = true; - + // 返回 信息字符串 String resutltString = "" ; - String token = request.getHeader ( "Authorization") ; + + String token = null; + TokenResult tokenResult = null; + try { - JwtUtils.parseToken(token); + token = request.getHeader ( "Authorization") ; + }catch (Exception e) { + resutltString = "Header Must param get Error"; + result = false; + } + + try { + // 判断是否 token 是否能合法解析 + tokenResult = JwtUtils.parseToken(token); }catch (SignatureVerificationException e){ resutltString="token sign error"; result=false; @@ -33,10 +52,43 @@ public class JwtInterceptor implements HandlerInterceptor { resutltString="token AlgorithmMismatchException"; result=false; }catch (Exception e) { - resutltString = "token invalid"; + resutltString = "token gotError"; result = false; } + if(! StringUtils.isBlank(token)){ + + // 判断 解析传入token + if (tokenResult == null ) { + resutltString = "token invalid "; + result = false; + }else{ + String phone = tokenResult.getPhone(); + String indentiny = tokenResult.getIndentiny(); + // 从redis中取出token + String rdisTokenKey = JwtUtils.getRdisTokenKey(phone, indentiny); + String redisToken = redisTemplate.opsForValue().get(rdisTokenKey); + + // 判断 redis 中是否存在值 + if(StringUtils.isBlank(redisToken) ){ + resutltString = "token invalid "; + result = false; + } + if(!StringUtils.equals(token.trim(),redisToken.trim())){ + resutltString = "token Has invalid "; + result = false; + }else{ + resutltString = "token verfiy pass "; + result = true; + } + } + }else{ + resutltString = "token invalid "; + result = false; + } + + + // 当 token 获取异常,则向前端输出 失败 if (!result){ PrintWriter out = response.getWriter(); out.print(JSONObject.fromObject( ResponseResult.fail(resutltString) ).toString()); 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 6fc2d39..41ca7e0 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,12 +9,12 @@ import com.mashibing.internalcommon.request.VerificationCodeDTO; import com.mashibing.internalcommon.response.NumberCodeResponse; import com.mashibing.internalcommon.response.TokenResponse; import com.mashibing.internalcommon.util.JwtUtils; -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.stereotype.Service; +import java.time.Duration; import java.util.concurrent.TimeUnit; @Service @@ -26,13 +26,9 @@ public class VerificationCodeService { @Autowired private ServicePassengerUserCLient servicePassengerUserCLient; - - @Autowired private StringRedisTemplate redisTemplate; - private String prefixKey = "passenger-verification-code-"; - /** * 根据 传入手机号 生成验证码并存入redis @@ -46,7 +42,7 @@ public class VerificationCodeService { String numberCode = numberCodeResponse.getData().getNumberCode(); // 存入redis - String redisKey = getRdisKey(passengerPhone); + String redisKey = JwtUtils.getRdisVeriCodeKey(passengerPhone); redisTemplate.opsForValue().set(redisKey,numberCode,2, TimeUnit.MINUTES); // 返回处理结果 @@ -62,8 +58,8 @@ public class VerificationCodeService { public ResponseResult checkCode(String passengerPhone,String verificationCode){ // 根据 key前缀+号码 从redis取出对应 校验码比较 - String redisKey = getRdisKey(passengerPhone); - String codeRedis = redisTemplate.opsForValue().get(redisKey); + String redisVeriCodeKey = JwtUtils.getRdisVeriCodeKey(passengerPhone); + String codeRedis = redisTemplate.opsForValue().get(redisVeriCodeKey); // 校验 验证码 是否相同 if(StringUtils.isBlank(codeRedis) || !StringUtils.equals(codeRedis,verificationCode) ){ @@ -74,10 +70,15 @@ public class VerificationCodeService { VerificationCodeDTO verificationCodeDTO = new VerificationCodeDTO(); verificationCodeDTO.setPassengerPhone(passengerPhone); servicePassengerUserCLient.loginOrRegister(verificationCodeDTO); - redisTemplate.delete(redisKey);// 使用后删除key + redisTemplate.opsForValue().set(redisVeriCodeKey,""); + Boolean delete = redisTemplate.delete(redisVeriCodeKey);// 使用后删除key // 颁布 token 令牌 String token = JwtUtils.gerneratorToken(passengerPhone, IndentinyConstant.PASSENGER_IDENTITY); + // 将 token 存入 redis 中 + String redisTokenKey = JwtUtils.getRdisTokenKey(passengerPhone, IndentinyConstant.PASSENGER_IDENTITY); + redisTemplate.opsForValue().set(redisTokenKey,token,30,TimeUnit.DAYS); + TokenResponse tokenResponse = new TokenResponse(); tokenResponse.setToken(token); @@ -85,8 +86,5 @@ public class VerificationCodeService { return ResponseResult.success(tokenResponse); } - private String getRdisKey(String passengerPhone){ - return prefixKey.trim() + passengerPhone.trim(); - } } diff --git a/internal-common/src/main/java/com/mashibing/internalcommon/util/JwtUtils.java b/internal-common/src/main/java/com/mashibing/internalcommon/util/JwtUtils.java index e192583..638ecf8 100644 --- a/internal-common/src/main/java/com/mashibing/internalcommon/util/JwtUtils.java +++ b/internal-common/src/main/java/com/mashibing/internalcommon/util/JwtUtils.java @@ -20,16 +20,18 @@ public class JwtUtils { private static final String JWT_KEY_INDENTINY = "indentiny"; + private static final String veriCodePrefix = "passenger-verification-code-"; + private static final String tokenPrefix = "passenger-verification-code-"; + /** * 获取 token字符串 */ - public static String gerneratorToken(String passengerPhone,String indentiny){ - // 准备 token过期时间 Date 类型 - Calendar calendar = Calendar.getInstance(); - calendar.add(Calendar.DATE,1); - Date date = calendar.getTime(); +// // 准备 token过期时间 Date 类型 -移交服务端进行控制 +// Calendar calendar = Calendar.getInstance(); +// calendar.add(Calendar.DATE,1); +// Date date = calendar.getTime(); // 使用 JWT 创建 token合成对象 builder JWTCreator.Builder builder = JWT.create(); @@ -38,8 +40,8 @@ public class JwtUtils { builder.withClaim(JWT_KEY_PHONE,passengerPhone); builder.withClaim(JWT_KEY_INDENTINY,indentiny); - // 设置 超时时间 - builder.withExpiresAt(date); + // 设置 超时时间 -移交服务端进行控制 +// builder.withExpiresAt(date); // 使用 builder对象的 sign 方法生成 token String sign = builder.sign(Algorithm.HMAC256(SIGN)); @@ -48,7 +50,7 @@ public class JwtUtils { } /** - * 解析 传入token 返回 初始有效数据内容 + * 解析 传入token 返回 原始有效数据内容 * @param token * @return */ @@ -56,8 +58,8 @@ public class JwtUtils { // 通过 JWT 的 required 以某种加密算法校验后 进行比对 DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token); // 获取有效数据内容 - String phone = verify.getClaim(JWT_KEY_PHONE).toString(); - String indentiny = verify.getClaim(JWT_KEY_INDENTINY).toString(); + String phone = verify.getClaim(JWT_KEY_PHONE).asString(); + String indentiny = verify.getClaim(JWT_KEY_INDENTINY).asString(); TokenResult result = new TokenResult(); result.setPhone(phone); @@ -66,7 +68,14 @@ public class JwtUtils { return result; } - + // 获取 验证码存入redis中的 key + public static String getRdisVeriCodeKey(String passengerPhone){ + return veriCodePrefix.trim() + passengerPhone.trim(); + } + // 获取 token 存入redis中的 key + public static String getRdisTokenKey(String phone,String indentiny){ + return tokenPrefix.trim() + phone.trim() + indentiny.trim(); + } // public static void main (String [ ] args ) { //