JJWT 全称Java Json Web Token。
而JWT是一种在两方之间传输信息的方法,在jwt的主体中编码的信息被称为claims。jwt的扩展形式是json,因此每个claim都是json对象中的一个键。
jwts增强了可验证性,接收都可以确定jwt没有通过验证签名来篡改。jwts可以加密签名成为jws,或加密成为jwe。
jwts生成的jwt的结果有三个部分的字符串,每个部分由“.”分隔。
1、每一部分都是base 64编码,称为header,必须指定用于签署jwt的算法。
2、第二部分是body,包含了jwt编码的所有声明。
3、第三部分是signature,它通过在头文件中指定的算法通过header和body的组合来计算。
header
{
"alg": "HS256"
}
body
{
"sub": "Joe"
在这种情况下,我们得到的信息是使用sha-256算法的HMAC来签署JWT,而且有一个claim sub与value Joe。claims包含一些标准的claims,所有claim都是可选的,并且是大小写敏感的。
1、iss
issuer,是签发该证书的负责人。
2、sub
subject,主体
3、aud
Audience,是指jwt的接受者。
4、exp
expiration time,过期时间。
5、nbf
Not before,开始日期
6、iat
issued at,是指jwt的发行时间
7、jti
jwt id,jwt提供唯一的标识符。
maven依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
编码解码
String compactJws = Jwts.builder()
.setSubject("Joe")
.compressWith(CompressionCodecs.DEFLATE)
.signWith(SignatureAlgorithm.HS512, key)
.compact();
try {
Jws<Claims> claims = Jwts.parser()
.requireSubject("Joe")
.require("hasMotorcycle", true)
.setSigningKey(key)
.parseClaimsJws(compactJws);
} catch (MissingClaimException e) {
// we get here if the required claim is not present
} catch (IncorrectClaimException e) {
// we get here if the required claim has the wrong value
}