Spring Boot 整合 jwt 流程操作(笔记)

Spring Boot 整合jwt

一、依赖引入

		
        
            com.auth0
            java-jwt
            3.8.2
        

二、Util工具类

public class JWTUtils {

    private static final String SIGN = "!sfdhfsfb";

    /**
     * 生成token header.payload.signature
     */
    public static String createToken(Map map){

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,7); //默认7天过期

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        //过期时间
        builder.withExpiresAt(instance.getTime());
        //payload
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });

        String token = builder.sign(Algorithm.HMAC256(SIGN));//签名signature

        return token;
    }

    /**
     * 验证token 合法性
     */
    public static void verify(String token){
        //创建验证对象
        JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

    /**
     * 获取token信息
     */
    public static DecodedJWT getTokenInfo(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        return verify;
    }
}

三、拦截器配置类

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

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

四、拦截器

public class JWTInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HashMap map = new HashMap<>();
        //获取请求头中的token
        String token = request.getHeader("token");
        try {
            JWTUtils.verify(token); //验证令牌
            return true; //放行请求
        }catch (SignatureVerificationException e){
            e.printStackTrace();
            map.put("msg","无效签名!");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("msg","token过期");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg","token算法不一致");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg","token无效!!");
        }
        map.put("state",false);
        //将map 转为 json 使用jackson
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}

五、测试token生成

/**
     * 令牌的生成
     */
   @Test
    void getToken(){
        Map map = new HashMap<>();

        map.put("id", "21");
        map.put("name", "xiaochen");

        String token = JWTUtils.createToken(map);

        System.out.println(token);
    }

你可能感兴趣的:(spring,boot,java,spring)