6.7JWT的负载(Payload)声明 Issuer ("iss") 返回签发者的名称值,如果没有在负载中定义则返回null String issuer = jwt.getIssuer(); Subject ("sub") 返回jwt所面向的用户的值,如果没有在负载中定义则返回null String subject = jwt.getSubject(); Audience ("aud") 返回该jwt由谁接收,如果没有在负载中定义则返回null List<String> audience = jwt.getAudience(); Expiration Time ("exp") 返回该jwt的过期时间,如果在负载中没有定义则返回null Date expiresAt = jwt.getExpiresAt(); Not Before ("nbf") Returns the Not Before value or null if it's not defined in the Payload. Date notBefore = jwt.getNotBefore(); Issued At ("iat") 返回在什么时候签发的,如果在负载中没有定义则返回null Date issuedAt = jwt.getIssuedAt(); JWT ID ("jti") 返回该jwt的唯一标志,如果在负载中没有定义则返回null String id = jwt.getId(); 自定义声明 在令牌有效负载中定义的附加声明可以通过调用getClaims()或 getClaim()和传递声明名来获得。即使无法找到声明,也将会有返回值。您可以通过调用claim.isNull()来检查声明的值是否为null。 Map<String, Claim> claims = jwt.getClaims(); //Key is the Claim name Claim claim = claims.get("isAdmin"); 或者: Claim claim = jwt.getClaim("isAdmin"); 当使用jwt.create()创建一个令牌时,您可以通过调用withClaim()来指定自定义声明,并同时传递名称和值。 String token = JWT.create() .withClaim("name", 123) .withArrayClaim("array", new Integer[]{1, 2, 3}) .sign(algorithm); 您还可以通过调用withClaim()来验证jwt.require()的自定义声明,并传递该名称和所需的值。 JWTVerifier verifier = JWT.require(algorithm) .withClaim("name", 123) .withArrayClaim("array", 1, 2, 3) .build(); DecodedJWT jwt = verifier.verify("my.jwt.token"); 提示:当前支持的自定义JWT声明创建和验证的类型是:Boolean, Integer, Double, String, Date 和Arrays。 6.8Claim Class 索赔类是索赔值的包装器。它允许您将索赔作为不同的类类型。可用的工具方法: 原始的: asBoolean(): 返回布尔值,如果不能转换返回null。 asInt(): 返回整数值,如果不能转换返回null。 asDouble(): 返回 Double 值,如果不能转换则返回null。 asLong(): 返回Long 值,如果不能转换则返回null。 asString(): 返回String值,如果不能转换则返回null。 asDate(): 返回 Date值,如果不能转换则返回null。 必须是一个数字日期 (Unix 系统时间戳). 注意,JWT标准指定所有的数字日期值必须以秒为单位。 自定义类型和集合: 要获得作为集合的声明,您需要提供要转换的内容的类类型 as(class): 返回 Class Type 的解析值. 对于集合,您应该使用asArray和asList方法。 asMap(): 返回被转换为 Map<String, Object>的值 asArray(class): 返回被转换成元素类型的 Class Type, or null if the value isn't a JSON Array. asList(class): 返回集合元素的 Class Type, or null if the value isn't a JSON Array. 如果不能将值转换为给定的类类型,则会抛出JWTDecodeException异常