JWT流程

先写jwt工具类

package com.bjpowernode.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

@Data
@Component
@ConfigurationProperties(prefix = "markhub.jwt")
public class JWTUtils {

    private static String KEY ="1231231231";
    public static String header ="Authorization";

    /**
     * 同过传进来map来构建jwt
     *
     * @param map
     * @return
     */
    public static String getToken(Map<String, String> map) {
        //创建jwt
        JWTCreator.Builder builder = JWT.create();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7);//设置7天过期时间
        //写入payload
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        //设置过期时间
        builder.withExpiresAt(instance.getTime());
        //设置代码加密
        String token = builder.sign(Algorithm.HMAC256(KEY));
        //把token返回出去
        return token;
    }

    /**
     * 验证token
     * 并解码jwt
     */

    public static DecodedJWT getToken(String jwt) {
        DecodedJWT verify = null;
        try {
            verify = JWT.require(Algorithm.HMAC256(KEY)).build().verify(jwt);
        } catch (JWTVerificationException e) {
            return null;
        } catch (IllegalArgumentException e) {
            return null;
        }
        return verify;
    }

    /**
     * 判断是否过期
     * @param decodedJWT
     * @return
     */
    public static boolean isTokenExpire(DecodedJWT decodedJWT) {
        return decodedJWT.getExpiresAt().before(new Date());
    }

}

在登录完成时添加jwt给前端请求头

  //生成jwt.并放置到请求头中
        String jwt = JWTUtils.getToken((Map<String, String>) MapUtil.builder().put("username", authentication.getName()));
        httpServletResponse.setHeader(JWTUtils.header,jwt);

编写JWT的Config类并实现WebMvcConfigurer接口

package com.bjpowernode.springboot.config;

import com.bjpowernode.springboot.interceptor.JWTInterceptor;
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 JWTConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new JWTInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/**");
    }
}

编写JWT拦截器,实现HandlerInterceptor接口

package com.bjpowernode.springboot.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.bjpowernode.springboot.Utils.JWTUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        Map map = new HashMap();
        try {
            JWTUtils.getToken(token);
            return true;
        } catch (TokenExpiredException e) {
            map.put("state", false);
            map.put("msg", "Token已经过期!!!");
        } catch (SignatureVerificationException e){
            map.put("state", false);
            map.put("msg", "签名错误!!!");
        } catch (AlgorithmMismatchException e){
            map.put("state", false);
            map.put("msg", "加密算法不匹配!!!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state", false);
            map.put("msg", "无效token~~");
        }
        String string = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(string);
        return false;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值