jwt使用

JSON Web Tokens - jwt.io
https://jwt.io/

依赖

FusionAuth/fusionauth-jwt: A simple to use Java 8 JWT Library. Verify, Sign, Encode, Decode all day.
https://github.com/fusionauth/fusionauth-jwt

<dependency>
      <groupId>io.fusionauth</groupId>
      <artifactId>fusionauth-jwt</artifactId>
      <version>3.0.0</version>
</dependency>

  

hello-world

/**
 * 1. 安装openssl
 * 2. 命令生成公钥(yue), 私钥
 * openssl genrsa -out rsa_private_key.pem 2048
 * openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
 */

// ==============生成token==================
// 构建RSA signer 使用 SHA-256 hash
File pri = new File(this.getClass().getClassLoader().getResource("rsa_private_key.pem").getPath());
byte[] bFile = Files.readAllBytes(pri.toPath());
Signer signer = RSASigner.newSHA256Signer(new String(bFile));

// 构建 JWT with an issuer(iss), issued at(iat), subject(sub) and expiration(exp)
JWT jwt = new JWT().setIssuer("www.acme.com")
		.setIssuedAt(ZonedDateTime.now(ZoneOffset.UTC))
		.setSubject("f1e33ab3-027f-47c5-bb07-8dd8ab37a2d3")
		.setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(60));

// Sign and encode the JWT to a JSON string representation
String encodedJWT = JWT.getEncoder().encode(jwt, signer);
System.out.println(encodedJWT);

// ==============解析token==================
// Build an RSA signer using a SHA-256 hash
File pub= new File(this.getClass().getClassLoader().getResource("rsa_private_key.pem").getPath());
Verifier verifier = RSAVerifier.newVerifier(pub.toPath());

// Verify and decode the encoded string JWT to a rich object
JWT jwt2 = JWT.getDecoder().decode(encodedJWT, verifier);

// Assert the subject of the JWT is as expected
System.out.println(jwt2.subject);

  

猜你喜欢

转载自www.cnblogs.com/startnow/p/10294752.html
jwt