//springboot integration redis+jwt Do double token Refresh login effective time
Prior knowledge :redis Fundamentals and understanding Spring Of RedisTemplate Basic usage of ( Not much here redis I've just been in touch ),MD5 Join us with password ( It was written in my previous blog ),JWT The login permission of is analyzed in the introduction
thinking : User password login ---->JwtInterceptor Interceptor ( Release landing request )--->Controller Login controller --> Password in the controller MD5/SHA Salting and densification
----> Verify user login information ---> Call if correct jwt Generate response header's token Token and set the validity period to 7 day , In response to the header token As key,
user name / Account number as value Deposit in redis(redis Inside token It's the second token--- The code uses Spring In RedisTemplate) And set the effective time as 2 hour ,
Then take the user account as key,tokne As value Deposit in redis Set the effective time in the response header token Half the effective time ( As a long time token Basis for regeneration )
Then put the generated response header token Put it in the response header and return to the front end -----> Access again blocked by interceptor and take out from the request token-->JWT Medium resolution token( Judge whether it is modified , Whether the response header is passed token Validity of )--->
If the validity period is not expired, the token As key from redis Take it out value, If value Certificate of existence not expired ( Log in again if expired ( Login status is double token The login status is within the valid time )) Then determine the token Is the effective time half over , How to judge ?
Get the user name directly from the private declaration / Account as key from redis Value , If the value is not null It doesn't need to be regenerated before it's expired token Direct refresh redis Effective time in , If the value is null In the response header token It's half time ,
According to the user id Find out the password of the changed user from the database and regenerate the response header token Reset at the same time redis In token
Here are the main code blocks :
redis Tools :
@Component
public class RedisUtil {
@Resource
public StringRedisTemplate stringRedisTemplate;
public String getKey(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
public void setKey(String key, Object value) {
stringRedisTemplate.opsForValue().set(key, value.toString());
}
public Long getExpire(String key) {
return stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
}
public void setExpire(String key, long timeOut, TimeUnit timeType) {
stringRedisTemplate.expire(key, timeOut, timeType);
}
public Boolean deleteKey(String key) {
return stringRedisTemplate.delete(key);
}
}
JWT Tools :
package com.myblog.wj.util;
import com.myblog.wj.entity.BlogUser;
import com.myblog.wj.service.BlogUserService;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Component
public class Jwt {
public final String JWT_SECRET_KEY= "wangJian";
public final String JWT_TOKEN_HEADER ="Authorization";
public final Long JWT_TOKEN_EXPIRTATION=2L;
public static boolean flag=false;// judge redis in token Expired or not ;
public static Date expireDate=null;
public static Date startDate=null;
public static String user_no=null;
@Resource
RedisUtil redisUtil;
@Resource
BlogUserService blogUserService;
public String CreateToken(BlogUser user){
// set up token head
Map<String,Object>map=new HashMap<>();
map.put("type","JWT");
map.put("alg","HS256");
// Set private claim
Map<String,Object>claims=new HashMap<>();
claims.put("user_id",user.getUser_id());
claims.put("user_name",user.getUser_name());
claims.put("user_no",user.getUser_no());
// Set response header token The effective time is 7 day // If the effective time of continuous access is more than half, this is regenerated token
Calendar calendar=Calendar.getInstance();
calendar.setTime(new Date(System.currentTimeMillis()));
calendar.set(Calendar.DATE,calendar.get(Calendar.DATE)+7);
expireDate=calendar.getTime();
String token=Jwts.builder()
.setClaims(claims)
.setHeader(map)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(expireDate)
.setSubject(user.getUser_id().toString())
.signWith(SignatureAlgorithm.HS256, JWT_SECRET_KEY)
.compact();
System.out.println("token="+token);
System.out.println("user:"+user);
// set up redis in token Valid for 2h, Set the response header at the same time token Rebuild or not ( No need for users to enter account password to steal token So as to reach the response head token Effective time refresh ) More than 4 Regenerate in days token
redisUtil.setKey(token,user.getUser_name());
redisUtil.setExpire(token,JWT_TOKEN_EXPIRTATION,TimeUnit.HOURS);
// As whether to refresh the response header token Basis of effective time of
redisUtil.setKey(user.getUser_no(),token);
redisUtil.setExpire(user.getUser_no(),4,TimeUnit.DAYS);
System.out.println(" take out token="+redisUtil.getKey(token));
return token;
}
// analysis token
public String AnalysisToken(String token) throws ServletException {
if (token!=null) {
try {
Claims claims = Jwts.parser()
.setSigningKey(JWT_SECRET_KEY)
.parseClaimsJws(token)
.getBody();
System.out.println(" It's here now token="+token);
// Refresh redis in token Determine whether to regenerate the new token
return RefreshToken(token
,JWT_TOKEN_EXPIRTATION,TimeUnit.HOURS,claims);
}catch (SignatureException e){
throw new ServletException(" Authentication failed !"+e.getMessage());
} catch (ExpiredJwtException e) {
redisUtil.deleteKey(token);
throw new ServletException(" Identity expired ");
}
}else {
return null;
}
}
// judge redis in token Expired or not
public boolean isExpiret(String token){
String user_name = redisUtil.getKey(token);
if (user_name == null || "".equals(user_name.trim())) {
return false;
}
return true;
}
// Refresh redis In token, At the same time, judge the token
public String RefreshToken(String token , long expiret,TimeUnit
timeType,Claims claims){
user_no=null;
// judge redis in token Expired or not
flag=isExpiret(token);
if (flag){
// If redis In token Not expired
// Determine the token Effective time If the token Regenerate if more than half of the effective time token
user_no=claims.get("user_no").toString();
if(redisUtil.getKey(user_no)==null){
token=CreateToken(blogUserService.SelectBlogUserByNoAndName(user_no));
System.out.println(" Rebuild token="+token);
}
redisUtil.setExpire(token, JWT_TOKEN_EXPIRTATION, TimeUnit.HOURS);
return token;
}else{
try {
throw new ServletException(" Identity expired !");
} catch (ServletException e) {
e.printStackTrace();
}
return null;
}
}
}
Technology
Daily Recommendation