JWT 简述

markdown ### 基础知识 ```text eyJhbGciOiJIUzI1NiJ9. eyJzdWIiOiJ1c2VyIiwiaWF0IjoxNjg0Mjg0MzIwLCJleHAi OjE2ODQyODc5MjAsImF1dGhvcml0aWVzIjoiUk9MRV9VU0VS In0._v9UewX5EzHudu9loOe_oRRAMEdlhBUdKP46PTowzsg 主要结构为: 标头.有效载荷.签名 ``` 1. head ```text echo "eyJhbGciOiJIUzI1NiJ9" | base64 -d {"alg":"HS256"} ``` 2. Payload ```text echo "eyJzdWIiOiJ1c2VyIiwiaWF0IjoxNjg0Mjg0MzIwLCJleHAiOjE2ODQyODc5MjAsImF1dGhv cml0aWVzIjoiUk9MRV9VU0VSIn0" | base64 -d {"sub":"user","iat":1684284320,"exp":1684287920,"authorities":"ROLE_USER"} ``` 3. signature ```text #无法解析用于保证 Jwt没有被篡改过 #创建示例 HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret) ``` ### 基础操作 #### 生成token ```text void creterJTW() { logger.info("生成token: "); String sign = JWT.create() .withClaim("name", "harlod") .withClaim("id",23234423) .withExpiresAt(Instant.now().plus(Duration.ofDays(10L))) #32位密钥 .sign(Algorithm.HMAC256("u9hg7gt96g@hui")); logger.info(sign); } ``` #### 验证token ```text void verifierJWT() { logger.info("验证: "); JWTVerifier verifier = JWT.require(Algorithm.HMAC256("u9hg7gt96g@hui")).build(); DecodedJWT decodedJWT = verifier.verify("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiaGFybG9kIiwiaWQiOjIzLCJleHAiOjE2ODUxNTQxNDV9.OydyzXBOsIN2mJsDV3R6AvgP3X4Inolu5Uj3SNYiYgU"); logger.info("name " + decodedJWT.getClaim("name").asString()); logger.info("id " + decodedJWT.getClaim("id").asInt()); logger.info(String.valueOf(decodedJWT.getExpiresAtAsInstant())); } ``` ```text #也可以通过这种方式创建 JWTCreator.Builder jwtCreator = JWT.create(); ``` ### 配置拦截器 ```text @Component public class JwtIntercepter implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 从request中获取token并调用验证 return false; } } ``` ```text @Configuration public class IntercepterConfig implements WebMvcConfigurer { @Autowired private JwtIntercepter jwtIntercepter; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(jwtIntercepter) .addPathPatterns(/user/**) .appPathPatterns(/home) .excludePathPatterns(/login); } } ```

评论