Java:java-jwt实现JsonWebToken

网友投稿 1091 2022-05-30

文档:https://github.com/auth0/java-jwt

依赖

com.auth0 java-jwt 3.4.0

1

2

3

4

5

6

7

代码示例

package com.mouday; 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; import org.junit.jupiter.api.Test; import java.util.Date; import java.util.Map; public class JwtDemo { //过期时间 120秒后 private long expire = 120; // 秘钥 private String secret = "123456"; @Test public void createJwt() { Date now = new Date(); Date expireDate = new Date(now.getTime() + expire * 1000); Algorithm algorithm = Algorithm.HMAC256(secret); String token = JWT.create() .withClaim("id", 12) // 增加Payload数据 .withExpiresAt(expireDate) // 过期时间 .sign(algorithm); System.out.println(token); } @Test public void decodeJwt() { String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTIsImV4cCI6MTYwNzg3MjM5NH0.J5ih6dffc7z3D2ckYDCe61JuhsQJLXjQuDIUGMip94s"; DecodedJWT jwt = JWT.decode(token); System.out.println(jwt.getToken()); System.out.println(jwt.getHeader()); System.out.println(jwt.getPayload()); System.out.println(jwt.getSignature()); // 获取Payload中的数据 Map claims = jwt.getClaims(); //Key is the Claim name Integer id = claims.get("id").asInt(); System.out.println(id); } @Test public void verifyJwt() { String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTIsImV4cCI6MTYwNzg3MjM5NH0.J5ih6dffc7z3D2ckYDCe61JuhsQJLXjQuDIUGMip94s"; Algorithm algorithm = Algorithm.HMAC256(secret); JWTVerifier verifier = JWT.require(algorithm).build(); //Reusable verifier instance try { verifier.verify(token); System.out.println("验证成功"); } catch (Exception e) { e.printStackTrace(); } } }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

Java:java-jwt实现JsonWebToken

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

Java

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:QGIS教程01--为什么要用QGIS?
下一篇:Tomcat-- bio、nio、apr模式简述及配置
相关文章