JWT生成与解析

官方解析地址: 官网地址

<!--JWT(Json Web Token)登录支持-->
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>

生成JWT

// JWT头部分信息【Header】
Map<String, Object> header = new HashMap<>();
header.put("alg", "HS256");
header.put("typ", "JWT");

// 载核【Payload】
Map<String, Object> payload = new HashMap<>();
payload.put("sub", "1234567890");
payload.put("name","John Doe");
payload.put("admin",true);

// 声明Token失效时间
Calendar instance = Calendar.getInstance();
instance.add(Calendar.SECOND,300);// 300s

// 生成Token
String token = Jwts.builder()
        .setHeader(header)// 设置Header
        .setClaims(payload) // 设置载核
        .setExpiration(instance.getTime())// 设置生效时间
        .signWith(SignatureAlgorithm.HS256,"secret") // 签名,这里采用私钥进行签名,不要泄露了自己的私钥信息
        .compact(); // 压缩生成xxx.xxx.xxx

System.out.println(token);

解析JWT

// 生成的token
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImV4cCI6MTY2MzI5NzQzMX0.Ju5EzKBpUnuIRhDG1SU0NwMGsd9Jl_8YBcMM6PB2C20";

// 解析head信息
JwsHeader jwsHeader = Jwts
        .parser()
        .setSigningKey("secret")
        .parseClaimsJws(token)
        .getHeader();

System.out.println(jwsHeader); // {typ=JWT, alg=HS256}
System.out.println("typ:"+jwsHeader.get("typ"));

// 解析Payload
Claims claims = Jwts
        .parser()
        .setSigningKey("secret")
        .parseClaimsJws(token)
        .getBody();
System.out.println(claims);// {sub=1234567890, name=John Doe, admin=true, exp=1663297431}
System.out.println("admin:"+claims.get("admin"));

// 解析Signature
String signature = Jwts
        .parser()
        .setSigningKey("secret")
        .parseClaimsJws(token)
        .getSignature();
System.out.println(signature); // Ju5EzKBpUnuIRhDG1SU0NwMGsd9Jl_8YBcMM6PB2C20
posted @ 2023-10-20 15:22  Kllin  阅读(90)  评论(0编辑  收藏  举报