下面列出了java.security.interfaces.RSAKey#com.auth0.jwt.algorithms.Algorithm 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void shouldNotOverwriteKeyIdIfAddedFromECDSAAlgorithms() throws Exception {
ECPrivateKey privateKey = (ECPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_EC_256, "EC");
ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class);
when(provider.getPrivateKeyId()).thenReturn("my-key-id");
when(provider.getPrivateKey()).thenReturn(privateKey);
String signed = JWTCreator.init()
.withKeyId("real-key-id")
.sign(Algorithm.ECDSA256(provider));
assertThat(signed, is(notNullValue()));
String[] parts = signed.split("\\.");
String headerJson = new String(Base64.decodeBase64(parts[0]), StandardCharsets.UTF_8);
assertThat(headerJson, JsonMatcher.hasEntry("kid", "my-key-id"));
}
private void verifyJwtToken(Response response) throws NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException, JWTVerificationException {
Token responseToken = response.readEntity(Token.class);
assertEquals("BEARER", responseToken.getTokenType().name());
String token = responseToken.getToken();
Algorithm algorithm = Algorithm.HMAC256("myJWT4Gr4v1t33_S3cr3t");
JWTVerifier jwtVerifier = JWT.require(algorithm).build();
DecodedJWT jwt = jwtVerifier.verify(token);
assertEquals(jwt.getSubject(),"[email protected]");
assertEquals("Jane", jwt.getClaim("firstname").asString());
assertEquals("gravitee-management-auth", jwt.getClaim("iss").asString());
assertEquals("[email protected]", jwt.getClaim("sub").asString());
assertEquals("[email protected]", jwt.getClaim("email").asString());
assertEquals("Doe", jwt.getClaim("lastname").asString());
}
@Test
public void succeedsWithValidTokenUsingDefaultClock() {
String token = JWT.create()
.withSubject("auth0|sdk458fks")
.withAudience(AUDIENCE)
.withIssuedAt(getYesterday())
.withExpiresAt(getTomorrow())
.withIssuer("https://" + DOMAIN + "/")
.withClaim("nonce", "nonce")
.sign(Algorithm.HMAC256("secret"));
DecodedJWT decodedJWT = JWT.decode(token);
SignatureVerifier verifier = mock(SignatureVerifier.class);
when(verifier.verifySignature(token)).thenReturn(decodedJWT);
IdTokenVerifier.init("https://" + DOMAIN + "/", AUDIENCE, verifier)
.build()
.verify(token, "nonce");
}
public Integer verifyTokenAndGetUserId(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer(ISSUSER)
.build();
DecodedJWT jwt = verifier.verify(token);
Map<String, Claim> claims = jwt.getClaims();
Claim claim = claims.get("userId");
return claim.asInt();
} catch (JWTVerificationException exception){
// exception.printStackTrace();
}
return 0;
}
@Test
public void shouldRemoveAudienceWhenPassingNull() throws Exception {
Algorithm algorithm = mock(Algorithm.class);
JWTVerifier verifier = JWTVerifier.init(algorithm)
.withAudience("John")
.withAudience((String) null)
.build();
assertThat(verifier.claims, is(notNullValue()));
assertThat(verifier.claims, not(hasKey("aud")));
verifier = JWTVerifier.init(algorithm)
.withAudience("John")
.withAudience((String[]) null)
.build();
assertThat(verifier.claims, is(notNullValue()));
assertThat(verifier.claims, not(hasKey("aud")));
}
@Test
public void shouldAuthenticateUsingJWK() throws Exception {
Jwk jwk = mock(Jwk.class);
JwkProvider jwkProvider = mock(JwkProvider.class);
KeyPair keyPair = RSAKeyPair();
when(jwkProvider.get(eq("key-id"))).thenReturn(jwk);
when(jwk.getPublicKey()).thenReturn(keyPair.getPublic());
JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience");
Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
String token = JWT.create()
.withAudience("test-audience")
.withIssuer("test-issuer")
.withHeader(keyIdHeader)
.sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate()));
Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);
Authentication result = provider.authenticate(authentication);
assertThat(result, is(notNullValue()));
assertThat(result, is(not(equalTo(authentication))));
}
@Test
public void shouldAddAudience() throws Exception {
String signed = JWTCreator.init()
.withAudience("Mark")
.sign(Algorithm.HMAC256("secret"));
assertThat(signed, is(notNullValue()));
assertThat(TokenUtils.splitToken(signed)[1], is("eyJhdWQiOiJNYXJrIn0"));
String signedArr = JWTCreator.init()
.withAudience("Mark", "David")
.sign(Algorithm.HMAC256("secret"));
assertThat(signedArr, is(notNullValue()));
assertThat(TokenUtils.splitToken(signedArr)[1], is("eyJhdWQiOlsiTWFyayIsIkRhdmlkIl19"));
}
/**
* decode AccountEntity from token
* f
*
* @param token token
* @return AccountEntity
*/
public static AccountEntity decodeToken(String token, String privateSecret) {
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(privateSecret)).build();
DecodedJWT jwt = verifier.verify(token);
// check expired date
if (Calendar.getInstance().getTime().after(jwt.getExpiresAt())) {
log.error("expired token at {}", jwt.getExpiresAt());
return null;
}
return new AccountEntity(jwt.getIssuer());
} catch (JWTVerificationException e) {
log.error("invalid jwt token", e);
return null;
}
}
@Test
public void shouldFailToAuthenticateUsingJWKIfMissingIssuerClaim() throws Exception {
Jwk jwk = mock(Jwk.class);
JwkProvider jwkProvider = mock(JwkProvider.class);
KeyPair keyPair = RSAKeyPair();
when(jwkProvider.get(eq("key-id"))).thenReturn(jwk);
when(jwk.getPublicKey()).thenReturn(keyPair.getPublic());
JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience");
Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
String token = JWT.create()
.withAudience("test-audience")
.withHeader(keyIdHeader)
.sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate()));
Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);
exception.expect(BadCredentialsException.class);
exception.expectMessage("Not a valid token");
exception.expectCause(Matchers.<Throwable>instanceOf(InvalidClaimException.class));
provider.authenticate(authentication);
}
/**
* WT生成Token.
* @param obj
* @return str
*/
public String createToken(Object obj) {
Date iatDate = new Date();
// expire time
Calendar nowTime = Calendar.getInstance();
nowTime.add(calendarField, calendarInterval);
Date expiresDate = nowTime.getTime();
// header Map
Map<String, Object> map = new HashMap<>();
map.put("alg", "HS256");
map.put("typ", "JWT");
JWTCreator.Builder builder = JWT.create().withHeader(map);
JSONObject json = JSONObject.parseObject(JSON.toJSONString(obj));
for (String key : json.keySet()) {
builder.withClaim(key, json.get(key).toString());
}
builder.withIssuedAt(iatDate); // sign time
builder.withExpiresAt(expiresDate); // expire time
String token = builder.sign(Algorithm.HMAC256(SECRET)); // signature
return token;
}
@Test
public void shouldFailToAuthenticateUsingJWKIfAudienceClaimDoesNotMatch() throws Exception {
Jwk jwk = mock(Jwk.class);
JwkProvider jwkProvider = mock(JwkProvider.class);
KeyPair keyPair = RSAKeyPair();
when(jwkProvider.get(eq("key-id"))).thenReturn(jwk);
when(jwk.getPublicKey()).thenReturn(keyPair.getPublic());
JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience");
Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
String token = JWT.create()
.withAudience("some-audience")
.withIssuer("test-issuer")
.withHeader(keyIdHeader)
.sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate()));
Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);
exception.expect(BadCredentialsException.class);
exception.expectMessage("Not a valid token");
exception.expectCause(Matchers.<Throwable>instanceOf(InvalidClaimException.class));
provider.authenticate(authentication);
}
@Bean
@Qualifier("jwk")
public JWTVerifier create(@Value("${jwt.issuer}") String issuer, @Value("${jwt.audience}") String audience)
throws JwkException, IOException {
UrlJwkProvider urlJwkProvider = new UrlJwkProvider(issuer);
RestTemplate restTemplate = new RestTemplate();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(restTemplate.getForObject(issuer + "/.well-known/jwks.json", String.class));
String kid = jsonNode.get("keys").get(0).get("kid").asText();
Jwk jwk = urlJwkProvider.get(kid);
return JWT.require(Algorithm.RSA256((RSAPublicKey) jwk.getPublicKey(), null))
.withIssuer(issuer)
.withAudience(audience)
.build();
}
@SuppressWarnings("unchecked")
@Test
public void shouldFailToAuthenticateUsingJWKIfKeyIdDoesNotMatch() throws Exception {
JwkProvider jwkProvider = mock(JwkProvider.class);
KeyPair keyPair = RSAKeyPair();
when(jwkProvider.get(eq("key-id"))).thenThrow(SigningKeyNotFoundException.class);
JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience");
Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
String token = JWT.create()
.withAudience("test-audience")
.withIssuer("test-issuer")
.withHeader(keyIdHeader)
.sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate()));
Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);
exception.expect(AuthenticationServiceException.class);
exception.expectMessage("Could not retrieve jwks from issuer");
exception.expectCause(Matchers.<Throwable>instanceOf(SigningKeyNotFoundException.class));
provider.authenticate(authentication);
}
@Test
public void succeedsWithValidTokenUsingDefaultClockAndHttpDomain() {
String token = JWT.create()
.withSubject("auth0|sdk458fks")
.withAudience(AUDIENCE)
.withIssuedAt(getYesterday())
.withExpiresAt(getTomorrow())
.withIssuer("http://" + DOMAIN + "/")
.withClaim("nonce", "nonce")
.sign(Algorithm.HMAC256("secret"));
DecodedJWT decodedJWT = JWT.decode(token);
SignatureVerifier verifier = mock(SignatureVerifier.class);
when(verifier.verifySignature(token)).thenReturn(decodedJWT);
IdTokenVerifier.init("http://" + DOMAIN + "/", AUDIENCE, verifier)
.build()
.verify(token, "nonce");
}
/**
* 生成签名
* @param account 帐号
* @return java.lang.String 返回加密的Token
* @author Wang926454
* @date 2018/8/31 9:07
*/
public static String sign(String account, String currentTimeMillis) {
try {
// 帐号加JWT私钥加密
String secret = account + Base64ConvertUtil.decode(encryptJWTKey);
// 此处过期时间是以毫秒为单位,所以乘以1000
Date date = new Date(System.currentTimeMillis() + Long.parseLong(accessTokenExpireTime) * 1000);
Algorithm algorithm = Algorithm.HMAC256(secret);
// 附带account帐号信息
return JWT.create()
.withClaim("account", account)
.withClaim("currentTimeMillis", currentTimeMillis)
.withExpiresAt(date)
.sign(algorithm);
} catch (UnsupportedEncodingException e) {
logger.error("JWTToken加密出现UnsupportedEncodingException异常:{}", e.getMessage());
throw new CustomException("JWTToken加密出现UnsupportedEncodingException异常:" + e.getMessage());
}
}
public Integer verifyTokenAndGetUserId(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer(ISSUSER)
.build();
DecodedJWT jwt = verifier.verify(token);
Map<String, Claim> claims = jwt.getClaims();
Claim claim = claims.get("userId");
return claim.asInt();
} catch (JWTVerificationException exception){
// exception.printStackTrace();
}
return 0;
}
@Test
@SuppressWarnings("unchecked")
public void shouldAcceptCustomClaimWithNullListAndRemoveClaim() throws Exception {
String jwt = JWTCreator.init()
.withClaim("list", "stubValue")
.withClaim("list", (List<String>) null)
.sign(Algorithm.HMAC256("secret"));
assertThat(jwt, is(notNullValue()));
String[] parts = jwt.split("\\.");
String body = new String(Base64.decodeBase64(parts[1]), StandardCharsets.UTF_8);
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = (Map<String, Object>) mapper.readValue(body, Map.class);
assertThat(map, anEmptyMap());
}
@Test
public void shouldThrowWhenExpectedArrayClaimIsMissing() throws Exception {
exception.expect(InvalidClaimException.class);
exception.expectMessage("The Claim 'missing' value doesn't match the required one.");
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcnJheSI6WzEsMiwzXX0.wKNFBcMdwIpdF9rXRxvexrzSM6umgSFqRO1WZj992YM";
JWTVerifier.init(Algorithm.HMAC256("secret"))
.withArrayClaim("missing", 1, 2, 3)
.build()
.verify(token);
}
@Test
public void shouldAddIssuer() throws Exception {
String signed = JWTCreator.init()
.withIssuer("auth0")
.sign(Algorithm.HMAC256("secret"));
assertThat(signed, is(notNullValue()));
assertThat(TokenUtils.splitToken(signed)[1], is("eyJpc3MiOiJhdXRoMCJ9"));
}
@Test
public void shouldValidateIssuer() throws Exception {
String token = "eyJhbGciOiJIUzI1NiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.mZ0m_N1J4PgeqWmi903JuUoDRZDBPB7HwkS4nVyWH1M";
DecodedJWT jwt = JWTVerifier.init(Algorithm.HMAC256("secret"))
.withIssuer("auth0")
.build()
.verify(token);
assertThat(jwt, is(notNullValue()));
}
@Test
public void shouldRemoveIssuerWhenPassingNullReference() throws Exception {
Algorithm algorithm = mock(Algorithm.class);
JWTVerifier verifier = JWTVerifier.init(algorithm)
.withIssuer((String) null)
.build();
assertThat(verifier.claims, is(notNullValue()));
assertThat(verifier.claims, not(hasKey("iss")));
verifier = JWTVerifier.init(algorithm)
.withIssuer((String[]) null)
.build();
assertThat(verifier.claims, is(notNullValue()));
assertThat(verifier.claims, not(hasKey("iss")));
verifier = JWTVerifier.init(algorithm)
.withIssuer()
.build();
assertThat(verifier.claims, is(notNullValue()));
assertThat(verifier.claims, not(hasKey("iss")));
String emptyIss = " ";
verifier = JWTVerifier.init(algorithm)
.withIssuer(emptyIss)
.build();
assertThat(verifier.claims, is(notNullValue()));
assertThat(verifier.claims, hasEntry("iss", Collections.singletonList(emptyIss)));
}
@SuppressWarnings("RedundantCast")
@Test
public void shouldAddDefaultLeewayToDateClaims() throws Exception {
Algorithm algorithm = mock(Algorithm.class);
JWTVerifier verifier = JWTVerifier.init(algorithm)
.build();
assertThat(verifier.claims, is(notNullValue()));
assertThat(verifier.claims, hasEntry("iat", (Object) 0L));
assertThat(verifier.claims, hasEntry("exp", (Object) 0L));
assertThat(verifier.claims, hasEntry("nbf", (Object) 0L));
}
@Test
public void shouldRefuseCustomClaimForNullMapKey() throws Exception {
Map<String, Object> data = new HashMap<>();
data.put(null, "subValue");
exception.expect(IllegalArgumentException.class);
JWTCreator.init()
.withClaim("pojo", data)
.sign(Algorithm.HMAC256("secret"));
}
/**
* Description: 解密jwt
*
* @param token token
* @param secret secret
* @return java.util.Map<java.lang.String , com.auth0.jwt.interfaces.Claim>
* @author fanxb
* @date 2019/3/4 18:14
*/
public static Map<String, Claim> decode(String token, String secret) {
if (token == null || token.length() == 0) {
throw new CustomException("token为空:" + token);
}
Algorithm algorithm = Algorithm.HMAC256(secret);
JWTVerifier jwtVerifier = JWT.require(algorithm).build();
DecodedJWT decodedJWT = jwtVerifier.verify(token);
return decodedJWT.getClaims();
}
private String createToken() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
Algorithm algorithm = Algorithm.RSA256((
RSAPublicKey) keyPair.getPublic(), (RSAPrivateKey) keyPair.getPrivate());
return JWT.create()
.withExpiresAt(Date.from(Instant.now().plusSeconds(120)))
.withClaim("uid", "test")
.sign(algorithm);
}
@Test
public void shouldFailToAuthenticateUsingSecretIfMissingIssuerClaim() throws Exception {
JwtAuthenticationProvider provider = new JwtAuthenticationProvider("secret".getBytes(), "test-issuer", "test-audience");
String token = JWT.create()
.withAudience("test-audience")
.sign(Algorithm.HMAC256("secret"));
Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);
exception.expect(BadCredentialsException.class);
exception.expectMessage("Not a valid token");
exception.expectCause(Matchers.<Throwable>instanceOf(InvalidClaimException.class));
provider.authenticate(authentication);
}
@Test
public void shouldThrowOnInvalidCustomClaimValueOfTypeString() throws Exception {
exception.expect(InvalidClaimException.class);
exception.expectMessage("The Claim 'name' value doesn't match the required one.");
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjpbInNvbWV0aGluZyJdfQ.3ENLez6tU_fG0SVFrGmISltZPiXLSHaz_dyn-XFTEGQ";
JWTVerifier.init(Algorithm.HMAC256("secret"))
.withClaim("name", "value")
.build()
.verify(token);
}
@Test
public void shouldFailToAuthenticateUsingSecretIfIssuerClaimDoesNotMatch() throws Exception {
JwtAuthenticationProvider provider = new JwtAuthenticationProvider("secret".getBytes(), "test-issuer", "test-audience");
String token = JWT.create()
.withAudience("test-audience")
.withIssuer("some-issuer")
.sign(Algorithm.HMAC256("secret"));
Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);
exception.expect(BadCredentialsException.class);
exception.expectMessage("Not a valid token");
exception.expectCause(Matchers.<Throwable>instanceOf(InvalidClaimException.class));
provider.authenticate(authentication);
}
public String createToken(Integer userId){
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
Map<String, Object> map = new HashMap<String, Object>();
Date nowDate = new Date();
// 过期时间:2小时
Date expireDate = getAfterDate(nowDate,0,0,0,2,0,0);
map.put("alg", "HS256");
map.put("typ", "JWT");
String token = JWT.create()
// 设置头部信息 Header
.withHeader(map)
// 设置 载荷 Payload
.withClaim("userId", userId)
.withIssuer(ISSUSER)
.withSubject(SUBJECT)
.withAudience(AUDIENCE)
// 生成签名的时间
.withIssuedAt(nowDate)
// 签名过期的时间
.withExpiresAt(expireDate)
// 签名 Signature
.sign(algorithm);
return token;
} catch (JWTCreationException exception){
exception.printStackTrace();
}
return null;
}
@Test
public void shouldThrowOnInvalidNotBeforeIfPresent() throws Exception {
exception.expect(InvalidClaimException.class);
exception.expectMessage(startsWith("The Token can't be used before"));
Clock clock = mock(Clock.class);
when(clock.getToday()).thenReturn(new Date(DATE_TOKEN_MS_VALUE - 1000));
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE0Nzc1OTJ9.wq4ZmnSF2VOxcQBxPLfeh1J2Ozy1Tj5iUaERm3FKaw8";
JWTVerifier.BaseVerification verification = (JWTVerifier.BaseVerification) JWTVerifier.init(Algorithm.HMAC256("secret"));
verification
.build(clock)
.verify(token);
}