//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 :
public class RedisUtil {
    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;

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;
RedisUtil redisUtil;
    BlogUserService blogUserService;

    public String CreateToken(BlogUser user){
        // set up token head
        Map<String,Object>map=new HashMap<>();
        // Set private claim
        Map<String,Object>claims=new HashMap<>();
        // 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()));
        String token=Jwts.builder()
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .signWith(SignatureAlgorithm.HS256, JWT_SECRET_KEY)
// 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
        // As whether to refresh the response header token Basis of effective time of
        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()
                System.out.println(" It's here now token="+token);
                // Refresh redis in token Determine whether to regenerate the new token
                return RefreshToken(token
            }catch (SignatureException e){
                throw new ServletException(" Authentication failed !"+e.getMessage());

            } catch (ExpiredJwtException e) {
                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){
        // judge redis in token Expired or not
        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
                System.out.println(" Rebuild token="+token);
            redisUtil.setExpire(token, JWT_TOKEN_EXPIRTATION, TimeUnit.HOURS);
            return token;
            try {
                throw new ServletException(" Identity expired !");
            } catch (ServletException e) {
            return null;


©2019-2020 Toolsou All rights reserved,
First knowledge python Skills summary GDOI2019 travels c Linguistic 5 Three common sorting methods Python Basic knowledge and notes " Cephalosporin wine Say go and go "? DANGER ! Don't drink alcohol when taking these drugs Thorough explanation from Zhongtai vue The component page height is adaptive according to the screen size Classical algorithm - recursion ( The case of raw rabbit ) Big data tells you , How tired are Chinese women about keras use fit_generator Encountered in StopIteration