下面列出了io.jsonwebtoken.IncorrectClaimException#com.auth0.jwt.exceptions.InvalidClaimException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void shouldFailToAuthenticateUsingJWKIfMissingAudienceClaim() 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()
.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);
}
@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);
}
@Test
public void shouldFailToAuthenticateUsingJWKIfIssuerClaimDoesNotMatch() 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("some-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);
}
@Test
public void shouldFailToAuthenticateUsingJWKIfIssuerClaimDoesNotMatchAllowedIssuers() 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, new String[]{"test-issuer1", "test-issuer2"}, "test-audience");
Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
String token = JWT.create()
.withAudience("test-audience")
.withIssuer("some-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);
}
@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);
}
@Test
public void shouldFailToAuthenticateUsingSecretIfMissingAudienceClaim() throws Exception {
JwtAuthenticationProvider provider = new JwtAuthenticationProvider("secret".getBytes(), "test-issuer", "test-audience");
String token = JWT.create()
.withIssuer("test-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);
}
@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 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);
}
@Test
public void shouldFailToAuthenticateUsingSecretIfIssuerClaimDoesNotMatchIssuersArray() throws Exception {
JwtAuthenticationProvider provider = new JwtAuthenticationProvider("secret".getBytes(), new String[]{"test-issuer1", "test-issuer2"}, "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);
}
@Test
public void shouldFailToAuthenticateUsingSecretIfAudienceClaimDoesNotMatch() throws Exception {
JwtAuthenticationProvider provider = new JwtAuthenticationProvider("secret".getBytes(), "test-issuer", "test-audience");
String token = JWT.create()
.withAudience("some-audience")
.withIssuer("test-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);
}
@Test(expectedExceptions = {BadJWTException.class, InvalidJwtException.class, InvalidClaimException.class, IncorrectClaimException.class},
description = "Illustrate validation of issuer")
public void testBadIssuer() throws Exception {
HashSet<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
invalidFields.add(TokenUtils.InvalidClaims.ISSUER);
String token = TokenUtils.generateTokenString("/Token1.json", invalidFields);
RSAPublicKey publicKey = (RSAPublicKey) TokenUtils.readPublicKey("/publicKey.pem");
int expGracePeriodSecs = 60;
validateToken(token, publicKey, TEST_ISSUER, expGracePeriodSecs);
}
/**
* Emit a token that claims only a subject (`alice`). Because this is a SIMPLE token, it essentially needs to do only
* two things: identify the account that the token is good for, and prove that whoever generated the token has the
* shared-secret. Note that while simple, this does not provide very good security since a compromised token can be
* reused forever, potentially without being easy to detect.
*/
private static void emitHs256Jwt() {
final String jwtString = JWT.create()
.withSubject(SUBJECT)
.sign(ALGORITHM_HS256);
LOGGER.info("JWT: {}", jwtString);
LOGGER.info("JWT Length (bytes): {}", jwtString.length());
// Log the JWT claims...
JWT.decode(jwtString).getClaims().forEach((key, value) ->
LOGGER.info("Claim -> \"{}\":\"{}\"", key, value.asString()
));
// Valid token...
final Verification verification = JWT.require(ALGORITHM_HS256).withSubject(SUBJECT);
// Valid token...
verification.build().verify(jwtString);
// Invalid token...
try {
verification.withSubject("bob").build().verify(jwtString);
throw new RuntimeException("Verify should have failed");
} catch (InvalidClaimException e) {
LOGGER.info("Invalid JWT for `bob` did not verify, as expected.");
}
}
/**
* Emit a JWT that has enhanced security.
*/
private static void emitHs256JwtWithExpiry() {
final String jwtString = JWT.create()
.withSubject(SUBJECT)
.withExpiresAt(Date.from(Instant.now().plus(730, ChronoUnit.DAYS)))
.sign(ALGORITHM_HS256);
LOGGER.info("JWT: {}", jwtString);
LOGGER.info("JWT Length (bytes): {}", jwtString.length());
// Log the JWT claims...
JWT.decode(jwtString).getClaims().forEach((key, value) ->
LOGGER.info("Claim -> \"{}\":\"{}\"", key, value.asString()
));
// Valid token...
final Verification verification = JWT.require(ALGORITHM_HS256).withSubject(SUBJECT);
// Valid token...
verification.build().verify(jwtString);
// Invalid token...
try {
verification.withSubject("bob").build().verify(jwtString);
throw new RuntimeException("Verify should have failed");
} catch (InvalidClaimException e) {
LOGGER.info("Invalid JWT for `bob` did not verify, as expected.");
}
}
/**
* Verifies the JSON Web Token with the secret key.
*
* @param token JSON Web Token to be verified
* @return decoded Token
*/
public DecodedJWT verify(String token) {
byte[] secret = secretKeyService.getSecretKey().getEncoded();
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).withIssuer("coderadar").build();
try {
return verifier.verify(token);
} catch (SignatureVerificationException | InvalidClaimException e) {
return null;
}
}
@Test
public void shouldThrowOnInvalidIssuer() throws Exception {
exception.expect(InvalidClaimException.class);
exception.expectMessage("The Claim 'iss' value doesn't match the required issuer.");
String token = "eyJhbGciOiJIUzI1NiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.mZ0m_N1J4PgeqWmi903JuUoDRZDBPB7HwkS4nVyWH1M";
JWTVerifier.init(Algorithm.HMAC256("secret"))
.withIssuer("invalid")
.build()
.verify(token);
}
@Test
public void shouldThrowOnNullIssuer() throws Exception {
exception.expect(InvalidClaimException.class);
exception.expectMessage("The Claim 'iss' value doesn't match the required issuer.");
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M";
JWTVerifier.init(Algorithm.HMAC256("secret"))
.withIssuer("auth0")
.build()
.verify(token);
}
@Test
public void shouldThrowOnInvalidSubject() throws Exception {
exception.expect(InvalidClaimException.class);
exception.expectMessage("The Claim 'sub' value doesn't match the required one.");
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.Rq8IxqeX7eA6GgYxlcHdPFVRNFFZc5rEI3MQTZZbK3I";
JWTVerifier.init(Algorithm.HMAC256("secret"))
.withSubject("invalid")
.build()
.verify(token);
}
@Test
public void shouldThrowOnInvalidAudience() throws Exception {
exception.expect(InvalidClaimException.class);
exception.expectMessage("The Claim 'aud' value doesn't contain the required audience.");
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.Rq8IxqeX7eA6GgYxlcHdPFVRNFFZc5rEI3MQTZZbK3I";
JWTVerifier.init(Algorithm.HMAC256("secret"))
.withAudience("nope")
.build()
.verify(token);
}
@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 shouldThrowWhenExpectedClaimIsMissing() throws Exception {
exception.expect(InvalidClaimException.class);
exception.expectMessage("The Claim 'missing' value doesn't match the required one.");
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGFpbSI6InRleHQifQ.aZ27Ze35VvTqxpaSIK5ZcnYHr4SrvANlUbDR8fw9qsQ";
JWTVerifier.init(Algorithm.HMAC256("secret"))
.withClaim("missing", "text")
.build()
.verify(token);
}
@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 shouldThrowOnInvalidCustomClaimValueOfTypeInteger() 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", 123)
.build()
.verify(token);
}
@Test
public void shouldThrowOnInvalidCustomClaimValueOfTypeDouble() 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", 23.45)
.build()
.verify(token);
}
@Test
public void shouldThrowOnInvalidCustomClaimValueOfTypeBoolean() 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", true)
.build()
.verify(token);
}
@Test
public void shouldThrowOnInvalidCustomClaimValueOfTypeDate() 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", new Date())
.build()
.verify(token);
}
@Test
public void shouldThrowOnInvalidCustomClaimValue() 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";
Map<String, Object> map = new HashMap<>();
map.put("name", new Object());
JWTVerifier verifier = new JWTVerifier(Algorithm.HMAC256("secret"), map, new ClockImpl());
verifier.verify(token);
}
@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);
}
@Test(expected = InvalidClaimException.class)
public void shouldThrowOnFutureIssuedAt() throws Exception {
Clock clock = mock(Clock.class);
when(clock.getToday()).thenReturn(new Date(DATE_TOKEN_MS_VALUE - 1000));
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE0Nzc1OTJ9.CWq-6pUXl1bFg81vqOUZbZrheO2kUBd2Xr3FUZmvudE";
JWTVerifier.BaseVerification verification = (JWTVerifier.BaseVerification) JWTVerifier.init(Algorithm.HMAC256("secret"));
DecodedJWT jwt = verification.build(clock).verify(token);
assertThat(jwt, is(notNullValue()));
}
@Test
public void shouldThrowOnInvalidIssuedAtIfPresent() 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.eyJpYXQiOjE0Nzc1OTJ9.0WJky9eLN7kuxLyZlmbcXRL3Wy8hLoNCEk5CCl2M4lo";
JWTVerifier.BaseVerification verification = (JWTVerifier.BaseVerification) JWTVerifier.init(Algorithm.HMAC256("secret"));
verification
.build(clock)
.verify(token);
}
@Test
public void shouldThrowOnInvalidJWTId() throws Exception {
exception.expect(InvalidClaimException.class);
exception.expectMessage("The Claim 'jti' value doesn't match the required one.");
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJqd3RfaWRfMTIzIn0.0kegfXUvwOYioP8PDaLMY1IlV8HOAzSVz3EGL7-jWF4";
JWTVerifier.init(Algorithm.HMAC256("secret"))
.withJWTId("invalid")
.build()
.verify(token);
}