use of io.jsonwebtoken.JwtParser in project athenz by yahoo.
the class DefaultOAuthJwtAccessTokenParserTest method testParse.
@Test
@SuppressWarnings("rawtypes")
public void testParse() throws Exception {
// mock internal parser
DefaultOAuthJwtAccessTokenParser parser = new DefaultOAuthJwtAccessTokenParser(baseKeyStore, this.classLoader.getResource("jwt_jwks.json").toString());
JwtParser jwtParserMock = Mockito.mock(JwtParser.class);
Field f = parser.getClass().getDeclaredField("parser");
f.setAccessible(true);
f.set(parser, jwtParserMock);
// parse error
Mockito.when(jwtParserMock.parseClaimsJws(null)).thenThrow(new NullPointerException());
assertThrows(OAuthJwtAccessTokenException.class, () -> parser.parse(null));
// parse success
String jwtString = "dummy-jwt-string";
Jws<Claims> jws = new Jws<Claims>() {
public JwsHeader getHeader() {
return null;
}
public Claims getBody() {
return null;
}
@Override
public String getSignature() {
return "dummy-jwt-signature";
}
};
Mockito.when(jwtParserMock.parseClaimsJws(jwtString)).thenReturn(jws);
OAuthJwtAccessToken token = parser.parse(jwtString);
assertNotNull(token);
assertTrue(token instanceof DefaultOAuthJwtAccessToken);
assertEquals(token.getSignature(), "dummy-jwt-signature");
}
use of io.jsonwebtoken.JwtParser in project yyl_example by Relucent.
the class JjwtDemo method main.
public static void main(String[] args) throws Exception {
long currentMillis = System.currentTimeMillis();
// JWT 生存时间(5秒)
long ttl = 5000;
// 生成JWT的时间
Date iat = new Date(currentMillis);
// 生成JWT失效时间
Date exp = new Date(currentMillis + ttl);
// 指定签名的时候使用的签名算法
SignatureAlgorithm algorithm = SignatureAlgorithm.HS256;
// 签名秘钥
String secret = "key";
// 本地的密码解码
byte[] encodedKey = Base64.getEncoder().encode(secret.getBytes());
JwtBuilder builder = Jwts.builder();
builder.setHeaderParam(JwsHeader.TYPE, JwsHeader.JWT_TYPE);
builder.setHeaderParam(JwsHeader.ALGORITHM, algorithm.getValue());
// JWT ID 可选
builder.setId("1");
// 主题
builder.setSubject("MySubject");
// 自定义属性;如果属性名与标准属性一致,会覆盖前面的标准属性
builder.claim("custom", "CustomClaim");
// 签发时间
builder.setIssuedAt(iat);
// 过期时间
builder.setExpiration(exp);
// 签名算法以及密匙
builder.signWith(algorithm, encodedKey);
// 生成Token
String token = builder.compact();
System.out.println(token);
// 获得JWT解析器
JwtParser parser = Jwts.parser().setSigningKey(encodedKey);
// 解析载荷为Claims
Jws<Claims> jws = parser.parseClaimsJws(token);
Claims claims = jws.getBody();
System.out.println(claims);
// 等待5秒
System.out.println("Wait 5 seconds!");
Thread.sleep(5000);
try {
// 这时候Token已经超时了,会抛出异常
parser.parseClaimsJws(token);
} catch (JwtException e) {
System.err.println(e);
}
}
Aggregations