java 简单token验证以及springboot2.0配置拦截器

package com.xx.xx.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import redis.clients.jedis.Jedis;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @auther
 * @Date 2019/2/14 14:23
 * @Description
 */
public class JWTUtils {
    /**
     * 过期时间 15分钟
     */
//    private static final long EXPIRE_TIME = 60 * 1000;
    private static final long EXPIRE_TIME = 15 * 60 * 1000;

    /**
     * token私钥
     */
    private static final String TOKEN_SECRET = "5e96cb3d2c054bbc89b1cf1380b98890";


    /**
     * 签名
     */
    public static String sign(String userName, String passWord) {
        //过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        //私钥机密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //设置头部信息
        Map header = new HashMap<>();
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        //附带username userid信息 生成签名
        return JWT.create().withHeader(header).withClaim("loginName", userName).withExpiresAt(date).sign(algorithm);
    }


    public static void main(String[] args) {
        System.out.println(UUID.randomUUID().toString());
        String sign = sign("123456", "123456");
        Jedis jedis = new Jedis("127.0.0.1",6379);
        jedis.set(sign,"1");
        jedis.expire(sign,120);
        System.out.println("key:=========="+sign);
//        String token ="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dpbk5hbWUiOiIxNTIxMDkxMTIyNSIsImV4cCI6MTU1MDIwMTA4MH0.WgKzBx0LsDshkFuBopJqEqn8giq0Lcoo18-PBTOSpsI";
        // 查看某个key的剩余生存时间,单位【秒】.永久生存或者不存在的都返回-1
//        Long ttl = jedis.ttl(token);
//        System.out.println("查看key001的剩余生存时间:"+ ttl);
//        //根据当前key:如果触发接口要增加redis失效时间
//        if(ttl != -1){
//            jedis.expire(token,ttl.intValue() + 520);
//        }else{
//            System.out.println("token已过期======================");
//        }
        boolean verify = verify(sign);
        System.out.println("---------token解密结果:"+ verify);
    }

    /**
     * token解密
     * @param token
     * @return
     */
    public static boolean verify(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT verify = verifier.verify(token);
            return true;
        } catch (Exception e){
            return false;
        }

    }
}

 

拦截器配置:

package com.xx.xx.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @auther 
 * @Date 2019/2/15 11:18
 * @Description  拦截器过滤token
 */
public class PassportInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle被调用");
        Jedis jedis = new Jedis("127.0.0.1",6379);
        String token = request.getHeader("token");
        Long ttl = jedis.ttl(token);
        System.out.println("redis剩余时间:"+ttl);
        jedis.get(token);
        boolean verify = JWTUtils.verify(token);
        System.out.println("token校验结果:"+ verify);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
     
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}

 

 

package com.xx.xx.config;

import com.xx.xx.common.PassportInterceptor;import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.*;

/**
 * @auther 
 * @Date 2019/2/15 11:29
 * @Description
 */

@Configuration
public class MywebConfig implements WebMvcConfigurer {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {

    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {

    }

    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {

    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {

    }

    @Override
    public void addFormatters(FormatterRegistry registry) {

    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new PassportInterceptor())
                .addPathPatterns("/user/**");
    }

}

你可能感兴趣的:(token验证,拦截器)