从redis中读取token,并校验

dev
hgx 1 year ago
parent 95740e2349
commit eed2d65b21

@ -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);

@ -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");
}
}

@ -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());

@ -4,7 +4,6 @@ import org.junit.Test;
import java.util.Hashtable;
import java.util.Map;
import java.util.TreeMap;
public class Test04 {

@ -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;i<k;i++){
System.out.println(i+"出现的次数"+counts[i]);
}
}
@Test
public void test04(){
int count = 0;
double x = 0.17;
int testTimes = 100000000;
for(int i=0;i<testTimes;i++){
if(xToXPower()<x){
count++;
}
}
System.out.println((double)count/ (double)testTimes);
System.out.println(Math.pow(x,2));
}
/**
* 01
* x,x010x)xx
* @return
*/
double xToXPower(){
return Math.max(Math.random(),Math.random());
}
@Test
public void test05(){
int count = 0;
int testTimes = 100000000;
for(int i=0;i<testTimes;i++){
if(f2() == 0){
count++;
}
}
System.out.println((double)count/ (double)testTimes);
}
int f1(){
return (int)(Math.random()*5)+1;
}
int f2(){
int ans = 0;
do{
ans = f1();
}while(ans==3);
return ans < 3 ? 0: 1;
}
int f3(){
return (f2()<< 2) + (f2()<<1) + f2()<<0;
}
@Test
public void test06(){
int count = 0;
int[] counts = new int[8];
int testTimes = 100000000;
for(int i=0;i<testTimes;i++){
int num = f3();
counts[num]++;
}
for(int i=0;i<counts.length;i++){
System.out.println(i+"出现的次数"+counts[i]);
}
}
int f4(){
int ans =0;
do{
ans = f3();
}while(ans == 7);
return ans;
}
@Test
public void test07(){
int count = 0;
int[] counts = new int[8];
int testTimes = 100000000;
for(int i=0;i<testTimes;i++){
int num = g();
counts[num]++;
}
for(int i=0;i<counts.length;i++){
System.out.println(i+"出现的次数"+counts[i]);
}
}
int g(){
return f4()+1;
}
//你只能知道。x会以固定概率返回0和1但是x的内容你看不到
int x(){
return Math.random()<0.84 ? 0:1;
}
//等概率返回0和1
int y(){
int ans =0;
do{
ans = x();
}while(ans == x());
// ans= 0 1
//ans = 1 0
return ans;
}
@Test
public void test08(){
int count = 0;
int testTimes = 100000000;
for(int i=0;i<testTimes;i++){
if(y() == 0){
count++;
}
}
System.out.println((double)count/ (double)testTimes);
}
// 返回一个数组arr,arr长度[0,maxLen-1],arr中的每个值[0,maxValue]
int[] lenRandomValueRandom(int maxLen,int maxValue){
int len = (int)(Math.random()*maxLen);
int[] ans = new int[len];
for(int i =0;i<len;i++){
ans[i] = (int)(Math.random()*maxValue);
}
return ans;
}
int[] copyArray(int[] arr){
int[] ans = new int[arr.length];
for(int i =0;i<arr.length;i++){
ans[i] = arr[i];
}
return ans;
}
//arr1和arr2一定等长
boolean isSorted(int[] arr){
if(arr.length <2){
return true;
}
int max = arr[0];
for(int i =1;i<arr.length;i++){
if(max >arr[i]){
return false;
}
max = Math.max(max,arr[i]);
}
return true;
}
@Test
public void test09(){
int maxLen =50;
int maxValue = 1000;
}
}

@ -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);

@ -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;
}
}
Loading…
Cancel
Save