环境:IDEA开发工具,JDK8 pom
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
Java测试代码
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.jupiter.api.Test;
import java.util.Date;
import java.util.UUID;
private long time = 1000*60*60*24;
private String signature="secret";
@Test
public void jwt(){
JwtBuilder builder = Jwts.builder();
String jwtToken = builder
.setHeaderParam("typ","JWT")
.setHeaderParam("alg","HS256")
.claim("username","tom")
.claim("role","admin")
.setSubject("admin-test")
.setExpiration(new Date(System.currentTimeMillis()+time))
.setId(UUID.randomUUID().toString())
.signWith(SignatureAlgorithm.HS256,signature)
.compact();
System.out.println(jwtToken);
}
@Test
public void parse(){
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRvbSIsInJvbGUiOiJhZG1pbiIsInN1YiI6ImFkbWluLXRlc3QiLCJleHAiOjE2Mjg5NDkwNTksImp0aSI6ImZkZDUxYWM5LTUyNTAtNGY0NC04NTc4LWMwNTU0MmMzY2Q4YyJ9.8HwfUWvRRbUGwV-UTIQHsateZTlUfwhg859C2WP2Gvg";
JwtParser parser = Jwts.parser();
Jws<Claims> claimsJws = parser.setSigningKey(signature).parseClaimsJws(token);
Claims claims = claimsJws.getBody();
System.out.println("username:"+claims.get("username"));
System.out.println("role:"+claims.get("role"));
System.out.println("ID:"+claims.getId());
System.out.println("Subject:"+claims.getSubject());
System.out.println("Expiration:"+claims.getExpiration());
String signature = claimsJws.getSignature();
System.out.println("signature:"+signature);
JwsHeader header = claimsJws.getHeader();
System.out.println("typ:"+header.get("typ"));
System.out.println("alg:"+header.get("alg"));
}
|