开发者

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

目录
  • 导入依赖
  • 配置文件
  • Jwt工具类
  • 定义拦截器
  • 配置拦截器
  • 总结

导入依赖

<!--引入JWT-->
<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>Java-jwt</artifactId>
    <versjavascription>3.4.0</version>
</dependency>

配置文件

# token配置
token:
  jwt:
    # 令牌自定义标识
    header: Authorization
    # 令牌密钥
    secret: ">?N<:{LwpWXX编程客栈#$%()(#*!()!KL<><MQLMNQNQJQK sdfkjsdrow32234545fdf"
    # 令牌有效期,单位分钟(默认30分钟)
    expireTime: 30

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;
 
/**
 * 登录Token的生成和解析
 */
@Component
public class JwtUtils {
 
    /**
     * token秘钥
     */
    public static String SECRET = "";
 
    /**
     * token 过期时间单位
     */
    public static final int calendarField = Calendar.MINUTE;
 
    /**
     * token 过期时间
     */
    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;
    }
 
    /**
     * JWT生成Token.<br/>
     * <p>
     * JWT构成: header, payload, signature
     *
     * @param map 登录成功后用户信息
     */
    public static String createToken(Map<String,String> map) {
        Date iatDate = new Date();
        // expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresDate = nowTime.getTime();
 
        // header Map
        Map<String, Object> 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));
    }
 
    /**
     * 解密token
     * @param token 传入的token
     * @return 解密后的结果
     */
    public static Map<String, Claim> 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.f编程客栈asterXML.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.heade}r")
    private String header;
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> 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 (SignatureVerificationExphpception e){
            map.put("msg","无效签名");
        } catch (TokenExpiredExceptionandroid 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.intercept.JWTInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
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 {
 
    @Autowired
    private JWTInterceptor jwtInterceptor;
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/index") // 拦截
                .excludePathPatterns("/hello"); // 不拦截
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜