栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot集成JWT的工具类与拦截器实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot集成JWT的工具类与拦截器实现

导入依赖



    com.auth0
    java-jwt
    3.4.0

配置文件

# token配置
token:
  jwt:
    # 令牌自定义标识
    header: Authorization
    # 令牌密钥
    secret: ">?N<:{LWPWXX#$%()(#*!()!KL<> 

Jwt工具类,包括token的生成,token的验证并返回存在负载中的用户信息

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

import com.auth0.jwt.JWTCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;


@Component
public class JwtUtils {

    
    public static String SECRET = "";

    
    public static final int calendarField = Calendar.MINUTE;

    
    public static int calendarInterval = 30;

    @Value("${token.jwt.secret}")
    public void setSECRET(String SECRET) {
        JwtUtils.SECRET = SECRET;
    }

    @Value("${token.jwt.expireTime}")
    public  void setCalendarInterval(int calendarInterval) {
        JwtUtils.calendarInterval = calendarInterval;
    }

    
    public static String createToken(Map map) {
        Date iatDate = new Date();
        // expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresDate = nowTime.getTime();

        // header Map
        Map header = new HashMap<>();
        header.put("alg", "HS256");
        header.put("typ", "JWT");

        // 创建 token
        // param backups {iss:Service, aud:APP}
        JWTCreator.Builder builder = JWT.create().withHeader(header); // header 

        map.forEach(builder::withClaim); // payload
        // 指定token过期签名 和 签名
        return builder.withExpiresAt(expiresDate).sign(Algorithm.HMAC256(SECRET));
    }

    
    public static Map verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            // token 校验失败, 抛出Token验证非法异常
             e.printStackTrace();
        }
        assert jwt != null;
        return jwt.getClaims();
    }
}

定义拦截器:对需要token验证的接口进行拦截

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lixianhe.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

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

@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Value("token.jwt.header")
    private String header;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map map = new HashMap<>();
        // 获取请求头中的token
        String token = request.getHeader(header);
        if(token ==null){
            response.setStatus(401);
            return false;
        }
        try {
            // 验证token,返回token中的信息
            JwtUtils.verifyToken(token);
            return true;
        }catch (SignatureVerificationException e){
            map.put("msg","无效签名");
        } catch (TokenExpiredException e){
            map.put("msg","token过期");
        }catch (AlgorithmMismatchException e){
            map.put("msg","签名算法不一致");
        }catch (Exception e){
            map.put("msg","token无效");
        }
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}

配置拦截器:配置对哪些路径拦截,哪些路径放行

import com.lixianhe.interceptors.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 InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new JWTInterceptor())
                .addPathPatterns("/user/*") // 拦截 /user/**
                .excludePathPatterns("/user/login"); // 不拦截 /user/login
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1000469.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号