JsonWebToken
<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>
生成密钥
@Test
public void generateBase64Key() {
SecretKey key = Jwts.SIG.HS256.key().build(); //or HS384.key() or HS512.key()
String secretString = Encoders.BASE64.encode(key.getEncoded());
System.out.println("生成的Base64密钥"+secretString);
}
// uXLMuWG1R1GaHthmnJXZyhHzWFmLxBRWbApJNkV8tDY=
package com.example;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.crypto.SecretKey;
import java.time.Instant;
import java.util.Date;
import io.jsonwebtoken.security.Keys;
@SpringBootTest
class SpringSecurityDemoApplicationTests {
// 私钥(base64)
private static final String secretBase64String = "uXLMuWG1R1GaHthmnJXZyhHzWFmLxBRWbApJNkV8tDY=";
@Test
public void generateBase64Key() {
SecretKey key = Jwts.SIG.HS256.key().build(); //or HS384.key() or HS512.key()
String secretString = Encoders.BASE64.encode(key.getEncoded());
System.out.println("生成的Base64密钥" + secretString);
}
@Test
public void generateToken() {
SecretKey secret = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretBase64String));
// token过期时间
Date exprireDate = Date.from(Instant.now().plusSeconds(300));
String jwt = Jwts.builder()
// 设置头部信息header
.header()
.add("typ", "JWT")
.add("alg", "HS256")
.and()
// 设置自定义负载信息payload
.claim("username", "zhangsan")
.claim("password", "123456")
// 过期日期,设置过期时间
.expiration(exprireDate)
// 签发时间
.issuedAt(new Date())
// 主题
.subject("TestApp")
// 签发者
.issuer("coderlzw")
// 签名
.signWith(secret)
.compact();
System.out.println("Generated JWT: " + jwt);
}
@Test
void parseToken() {
SecretKey secretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretBase64String));
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InpoYW5nc2FuIiwicGFzc3dvcmQiOiIxMjM0NTYiLCJleHAiOjE3MDExNjAzNTQsImlhdCI6MTcwMTE2MDA1NCwic3ViIjoiVGVzdEFwcCIsImlzcyI6ImNvZGVybHp3In0.LtRq0EWYbcee4I3z0hC3TjsIQmF6xp3xyfvvBoB6_xw";
Claims payload = Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload();
System.out.println(payload.get("username"));
System.out.println(payload.get("password"));
}
}
最后更新于
这有帮助吗?