jjwt库github地址:https://github.com/jwtk/jjwt
1.pom.xml引入包
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred -->
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
<!-- Uncomment this next dependency if you are using JDK 10 or earlier and you also want to use
RSASSA-PSS (PS256, PS384, PS512) algorithms. JDK 11 or later does not require it for those algorithms:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.60</version>
<scope>runtime</scope>
</dependency>
-->
2.测试用例
/**
* @Author: ltx
* @Date: 2020/9/16 10:07
* @Description: jwt例子,具体的jwt文档看这里
* https://github.com/jwtk/jjwt
*/
@Slf4j
public class JwtTest {
//jwt签名密钥,一般从配置文件读取
static final String SECRET = "58f85fcf-cdba-447c-8082-5ec61494c808";
//签名key
static final SecretKey key = Keys.hmacShaKeyFor(SECRET.getBytes());
@Test
public void jwtTest() {
//可以存任何值到自包含里面
HashMap<String, Object> mapValue = new HashMap<>(16);
mapValue.put("id", "1019");
mapValue.put("username", "admin_ltx");
String jws = Jwts.builder()
//数据体里面放数据(map)
.setClaims(mapValue)
.setId("8888")
.setIssuer("user007")
//头里面放数据(demo)
.setHeaderParam("kid", "myKeyId")
//设置签发时间
.setIssuedAt(new Date())
//不应该使用在此时间戳之后获得的JWT, 有效期7天, 过期会报ExpiredJwtException异常
.setExpiration(DateUtil.offsetDay(new Date(), 7))
//不应该使用在此时间戳之前获得的JWT, 相当于提前给你这个token,但到了这个时间之后才能使用
// .setNotBefore(new Date())
.setSubject("Joe")
//设置签名秘钥, SignatureAlgorithm.HS256 这个可以不写,默认就是使用SHA-256加密算法
.signWith(key, SignatureAlgorithm.HS256).compact();
// 13:52:26.401 [main] INFO com.qmy.crmadmin.JwtTest - eyJraWQiOiJteUtleUlkIiwiYWxnIjoiSFMyNTYifQ.eyJpZCI6IjEwMTkiLCJ1c2VybmFtZSI6ImFkbWluX2x0eCIsImlhdCI6MTYwMDIzNTU0NSwiZXhwIjoxNjAwODQwMzQ1LCJzdWIiOiJKb2UifQ.RhcOXuPXs_IJv4SEckS_mItR4ZOi2cM2CroFAmq_J5Y
log.info(jws);
//解析校验
try {
Jws<Claims> parserJws = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(jws);
// 13:52:26.457 [main] INFO com.qmy.crmadmin.JwtTest - header={kid=myKeyId, alg=HS256},body={id=1019, username=admin_ltx, iat=1600235545, exp=1600840345, sub=Joe},signature=RhcOXuPXs_IJv4SEckS_mItR4ZOi2cM2CroFAmq_J5Y
log.info("{}", parserJws);
} catch (MalformedJwtException e) {
log.error("JWT签名格式不对!");
log.error(e.getMessage(), e);
} catch (SignatureException e) {
log.error("JWT签名不匹配");
log.error(e.getMessage(), e);
} catch (ExpiredJwtException e) {
log.error("JWT签名过期了");
log.error(e.getMessage(), e);
}
}
}