赞
踩
组成:
JWT官方:JSON Web Tokens - jwt.io
本篇文章讲解的是下图中的库。GitHub地址:https://github.com/jwtk/jjwt
- <dependency>
- <groupId>io.jsonwebtoken</groupId>
- <artifactId>jjwt-api</artifactId>
- <version>0.12.3</version>
- </dependency>
- <dependency>
- <groupId>io.jsonwebtoken</groupId>
- <artifactId>jjwt-impl</artifactId>
- <version>0.12.3</version>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>io.jsonwebtoken</groupId>
- <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred -->
- <version>0.12.3</version>
- <scope>runtime</scope>
- </dependency>
- <!-- Uncomment this next dependency if you are using:
- - JDK 10 or earlier, and you want to use RSASSA-PSS (PS256, PS384, PS512) signature algorithms.
- - JDK 10 or earlier, and you want to use EdECDH (X25519 or X448) Elliptic Curve Diffie-Hellman encryption.
- - JDK 14 or earlier, and you want to use EdDSA (Ed25519 or Ed448) Elliptic Curve signature algorithms.
- It is unnecessary for these algorithms on JDK 15 or later.
- <dependency>
- <groupId>org.bouncycastle</groupId>
- <artifactId>bcprov-jdk18on</artifactId> or bcprov-jdk15to18 on JDK 7
- <version>1.76</version>
- <scope>runtime</scope>
- </dependency>
- -->
下面的代码介绍了两种密钥设置的方法。方法一自定义密钥(需满足长度>=256 bits);方法二:使用HMAC-SHA 算法生成密钥。
使用字符串当密钥的官方文档:https://github.com/jwtk/jjwt?tab=readme-ov-file#secretkey-formats
算法生成密钥的官方文档:https://github.com/jwtk/jjwt?tab=readme-ov-file#creating-safe-keys
- /**
- * 生成JWT
- */
- @Test
- public void testGenJwt2(){
- //设置令牌中携带的内容
- Map<String, Object> claims = new HashMap<>();
- claims.put("id", 1);
- claims.put("name", "tom");
-
- //生成密钥
- //方法一:自定义密钥(注:自定义必须满足base64编码后字节长度>=256 bits)
- //需要先对字符串进行BASE64编码才可以设置密钥,自定义密钥需要有足够的长度
- //SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64.decode("12345612qwwwwwwwwwwwwwwwwwwwwwwwwwwwww33333333333333333333333"));
-
- //方法二:生成密钥
- SecretKey key = Jwts.SIG.HS256.key().build();
-
- //生成JWT令牌
- String jwt = Jwts.builder()
- .claims(claims) //自定义内容(载荷)
- .expiration(new Date(System.currentTimeMillis() + 3600 * 1000))//设置有效期为1h
- .signWith(key, Jwts.SIG.HS256) //算法签名,(密钥,加密算法)
- .compact(); //返回为字符串类型的jwt令牌
- System.out.println(jwt);
- }
官网文档参考地址:https://github.com/jwtk/jjwt?tab=readme-ov-file#reading-a-jwt
- /**
- * 解析JWT
- */
- @Test
- public void testParseJwt2(){
- //将jwt令牌放到CharSequence类型中
- CharSequence jws = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoidG9tIiwiaWQiOjEsImV4cCI6NDEzMjI2NzkzMX0.knAZ5DiA-D4xvVGxk2NISfi3D59XR2Wmy_MAPCr1zzE";
- //设置解析令牌的密钥
- SecretKey secretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode("12345612qwwwwwwwwwwwwwwwwwwwwwwwwwwwww33333333333333333333333"));
- //解析jwt令牌,获取- Payload(有效载荷)
- Claims claims =Jwts.parser()
- .verifyWith(secretKey) // 传递密钥
- .build()
- .parseSignedClaims(jws) //传递jwt令牌参数
- .getPayload(); // 获取- Payload(有效载荷)
-
- System.out.println(claims);//打印内容:{name=tom, id=1, exp=4132267931}
- }
PS:不理解的,可以看一看它的源码中相关方法的注释,再结合官方文档,就很容易理解了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。