SpringBoot 之 JWT
介绍
官网
JSON Web Tokens - jwt.io
应用
依赖 Maven
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.0</version>
</dependency>
工具类 JWTUtils.class
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.Base64UrlCodec;import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;/*** @author ldz* @description TODO JWT工具类* @date 2021/10/10*/
public class JWTUtils {/*** 过期时间*/private static final long EXPRESSION_TIME = 1000 * 60 * 60 * 24;private static final String SECRET = "fnpt";private static final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;public static HashMap<String, String> getToken(String subject) throws Exception {Date st = new Date();Date et = new Date(st.getTime() + EXPRESSION_TIME);JwtBuilder builder = Jwts.builder().setSubject(subject).setIssuedAt(st).setExpiration(et).signWith(signatureAlgorithm, SECRET);HashMap<String, String> res = new HashMap<>();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");res.put("token", builder.compact());res.put("expiresTime", sdf.format(et));return res;}/*** 解析JWT** @param jwtStr* @return*/public static Claims parseJWT(String jwtStr) throws Exception {return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(jwtStr).getBody();}/*** 验证jwt** @param jwtStr* @return*/public static String validateJWT(String jwtStr) throws Exception {Claims claims = parseJWT(jwtStr);return JSON.toJSONString(claims);}/*** 不需要解析token的payload** @param token* @param cls* @param <T>* @return* @throws Exception*/public static <T> T decodeTokenPayload(String token, Class<T> cls) throws Exception {try {String payload = token.substring(token.indexOf(".") + 1, token.lastIndexOf("."));String jxh = new String(new Base64UrlCodec().decode(payload), "UTF-8");Object sub = JSON.parseObject(jxh).get("sub");return JSON.parseObject(sub.toString(), (Type) cls);} catch (Exception e) {e.printStackTrace();return cls.newInstance();}}public static JSONObject decodeTokenPayload(String token) throws Exception {String payload = token.substring(token.indexOf(".") + 1, token.lastIndexOf("."));String jxh = new String(new Base64UrlCodec().decode(payload), "UTF-8");Object sub = JSON.parseObject(jxh).get("sub");return JSON.parseObject(sub.toString());}
}
拦截器 JWTInterceptor.class
import com.alibaba.fastjson2.JSONObject;
import com.example.entity.vo.Response;
import com.example.utils.JWTUtils;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;@Slf4j
public class JWTInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {Response r = new Response();String token = request.getHeader("token");//获取请求头中的tokentry {JWTUtils.validateJWT(token);return true;//验证通过,就会去controller请求数据了} catch (SignatureException e) {r.setCode(-1).setMessage("签名异常");log.error(e.getMessage());} catch (ExpiredJwtException e) {log.error(e.getMessage());r.setCode(-1).setMessage("token过期");} catch (Exception e) {log.error(e.getMessage());r.setCode(-1).setMessage("无效签名!");}String jsonObject = JSONObject.toJSONString(r);response.setContentType("application/json;charset=UTF-8");response.getWriter().println(jsonObject);//错误信息发送回前台return false;}
}
总web配置 WebConfig.class
import com.example.intercepters.JWTInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new JWTInterceptor()).addPathPatterns("/**").excludePathPatterns("/tysl/**").excludePathPatterns("/login/*");//登陆接口放行}
}