下面列出了io.jsonwebtoken.IncorrectClaimException#org.jose4j.jwt.consumer.InvalidJwtException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testNonIntegerNumericDates() throws InvalidJwtException, MalformedClaimException
{
// JWT's NumericDate says that "non-integer values can be represented"
// https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-2
// I always just assumed that it could only be integers (maybe b/c of the former IntDate name )
// but looking at the text again it looks like maybe fractional values has always been possible.
// I'm not sure I see value in truly supporting sub-second accuracy (right now, anyway) but do want to
// ensure that we handle such values reasonably, if we receive them. This test checks that we don't fail
// and just truncate the sub-second part.
JwtClaims jcs = JwtClaims.parse("{\"sub\":\"brian.d.campbell\", \"nbf\":1430602000.173, \"iat\":1430602060.5, \"exp\":1430602600.77}");
Assert.assertThat(NumericDate.fromSeconds(1430602600), equalTo(jcs.getExpirationTime()));
Assert.assertThat(NumericDate.fromSeconds(1430602060), equalTo(jcs.getIssuedAt()));
Assert.assertThat(NumericDate.fromSeconds(1430602000), equalTo(jcs.getNotBefore()));
}
private static boolean isTokenExpired(String authorization) {
boolean expired = false;
String jwt = getJwtFromAuthorization(authorization);
if(jwt != null) {
JwtConsumer consumer = new JwtConsumerBuilder()
.setDisableRequireSignature()
.setSkipSignatureVerification()
.build();
try {
consumer.processToClaims(jwt);
} catch (InvalidJwtException e) {
if(e.hasExpired()) expired = true;
}
}
return expired;
}
public static String validateSharedResourceToken(Key key, String jwt) {
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
.setVerificationKey(key)
.setRelaxVerificationKeyValidation()
.build();
try {
JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
String subject = jwtClaims.getSubject();
try (JsonReader reader = Json.createReader(new StringReader(subject))) {
JsonObject subjectObject = reader.readObject(); // JsonParsingException
return subjectObject.getString(SHARED_ENTITY_UUID); // Npe
}
} catch (InvalidJwtException | MalformedClaimException | JsonParsingException | NullPointerException e) {
LOGGER.log(Level.FINE, "Cannot validate jwt token", e);
}
return null;
}
public static String validateEntityToken(Key key, String jwt) {
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
.setVerificationKey(key)
.setRelaxVerificationKeyValidation()
.build();
try {
JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
String subject = jwtClaims.getSubject();
try (JsonReader reader = Json.createReader(new StringReader(subject))) {
JsonObject subjectObject = reader.readObject(); // JsonParsingException
return subjectObject.getString(ENTITY_KEY); // Npe
}
} catch (InvalidJwtException | MalformedClaimException | JsonParsingException | NullPointerException e) {
LOGGER.log(Level.FINE, "Cannot validate jwt token", e);
}
return null;
}
@Test
public void testGetClaimsMap() throws InvalidJwtException, MalformedClaimException
{
String json = "{\"sub\":\"subject\",\"aud\":\"audience\",\"iss\":\"issuer\"," +
"\"jti\":\"mz3uxaCcLmQ2cwAV3oJxEQ\",\"exp\":1418906607," +
"\"email\":\"[email protected]\", \"name\":\"Joe User\", \"someclaim\":\"yup\"}";
JwtClaims jwtClaims = JwtClaims.parse(json);
Map<String, Object> claimsMap = jwtClaims.getClaimsMap(INITIAL_REGISTERED_CLAIM_NAMES);
Assert.assertThat(3, equalTo(claimsMap.size()));
claimsMap = jwtClaims.getClaimsMap();
Assert.assertThat(8, equalTo(claimsMap.size()));
Collection<String> claimNames = jwtClaims.getClaimNames(INITIAL_REGISTERED_CLAIM_NAMES);
Assert.assertThat(3, equalTo(claimNames.size()));
claimNames = jwtClaims.getClaimNames(Collections.singleton(AUDIENCE));
Assert.assertThat(7, equalTo(claimNames.size()));
claimNames = jwtClaims.getClaimNames();
Assert.assertThat(8, equalTo(claimNames.size()));
Assert.assertThat(json, is(equalTo(jwtClaims.getRawJson())));
}
@Test
public void missingRequiredClaim() throws Exception {
String token = TokenUtils.generateTokenString("/Token1.json");
PublicKey publicKey = TokenUtils.readPublicKey("/publicKey.pem");
JWTAuthContextInfo contextInfo = new JWTAuthContextInfo((RSAPublicKey) publicKey, TEST_ISSUER);
contextInfo.setRequiredClaims(Collections.singleton("something"));
JWTCallerPrincipalFactory factory = JWTCallerPrincipalFactory.instance();
final ParseException exception = assertThrows(ParseException.class, () -> factory.parse(token, contextInfo));
assertTrue(exception.getCause() instanceof InvalidJwtException);
}
@Test
public void missingRequiredClaims() throws Exception {
String token = TokenUtils.generateTokenString("/Token1.json");
PublicKey publicKey = TokenUtils.readPublicKey("/publicKey.pem");
JWTAuthContextInfo contextInfo = new JWTAuthContextInfo((RSAPublicKey) publicKey, TEST_ISSUER);
contextInfo.setRequiredClaims(Stream.of("something", "else").collect(toSet()));
JWTCallerPrincipalFactory factory = JWTCallerPrincipalFactory.instance();
final ParseException exception = assertThrows(ParseException.class, () -> factory.parse(token, contextInfo));
assertTrue(exception.getCause() instanceof InvalidJwtException);
}
@Test
public void requiredAndMissingClaims() throws Exception {
String token = TokenUtils.generateTokenString("/Token1.json");
PublicKey publicKey = TokenUtils.readPublicKey("/publicKey.pem");
JWTAuthContextInfo contextInfo = new JWTAuthContextInfo((RSAPublicKey) publicKey, TEST_ISSUER);
contextInfo.setRequiredClaims(
Stream.of("roles", "customObject", "customDoubleArray", "something").collect(toSet()));
JWTCallerPrincipalFactory factory = JWTCallerPrincipalFactory.instance();
final ParseException exception = assertThrows(ParseException.class, () -> factory.parse(token, contextInfo));
assertTrue(exception.getCause() instanceof InvalidJwtException);
}
@Test
public void testParseJwtSignedWith1024RsaKeyLengthDisallowed() throws Throwable {
KeyPair pair = KeyUtils.generateKeyPair(1024);
String jwt = TokenUtils.generateTokenString(pair.getPrivate(), "kid", "/Token1.json", null, null);
JWTAuthContextInfo context = new JWTAuthContextInfo((RSAPublicKey) pair.getPublic(), "https://server.example.com");
ParseException thrown = assertThrows("InvalidJwtException is expected",
ParseException.class, () -> parser.parse(jwt, context));
assertTrue(thrown.getCause() instanceof InvalidJwtException);
}
private void checkNameClaims(JwtContext jwtContext) throws InvalidJwtException {
JwtClaims claimsSet = jwtContext.getJwtClaims();
final boolean hasPrincipalClaim = claimsSet.getClaimValue(Claims.sub.name()) != null ||
claimsSet.getClaimValue(Claims.upn.name()) != null ||
claimsSet.getClaimValue(Claims.preferred_username.name()) != null;
if (!hasPrincipalClaim) {
throw PrincipalMessages.msg.claimNotFound(s -> new InvalidJwtException(s, emptyList(), jwtContext));
}
}
private void verifyRequiredClaims(JWTAuthContextInfo authContextInfo, JwtContext jwtContext) throws InvalidJwtException {
final Set<String> requiredClaims = authContextInfo.getRequiredClaims();
if (requiredClaims != null) {
if (!jwtContext.getJwtClaims().getClaimsMap().keySet().containsAll(requiredClaims)) {
if (PrincipalLogging.log.isDebugEnabled()) {
final String missingClaims = requiredClaims.stream()
.filter(claim -> !jwtContext.getJwtClaims().getClaimsMap().containsKey(claim))
.collect(Collectors.joining(","));
PrincipalLogging.log.missingClaims(missingClaims);
}
throw PrincipalMessages.msg.missingClaims(s -> new InvalidJwtException(s, emptyList(), jwtContext));
}
}
}
/**
* Validate a given token for a given channel.
*
* @param token the token to validate
* @param channel the channel
* @param filename the filename
*/
private static void validateToken(String token, String channel, String filename) {
AccessTokenFactory.lookupByToken(token).ifPresent(obj -> {
if (!obj.getValid()) {
halt(HttpStatus.SC_FORBIDDEN, "This token is not valid");
}
});
try {
JwtClaims claims = JWT_CONSUMER.processToClaims(token);
// enforce channel claim
Optional<List<String>> channelClaim = Optional.ofNullable(claims.getStringListClaimValue("onlyChannels"))
// new versions of getStringListClaimValue() return an empty list instead of null
.filter(l -> !l.isEmpty());
if (Opt.fold(channelClaim, () -> false, channels -> !channels.contains(channel))) {
halt(HttpStatus.SC_FORBIDDEN, "Token does not provide access to channel " + channel);
}
// enforce org claim
Optional<Long> orgClaim = Optional.ofNullable(claims.getClaimValue("org", Long.class));
Opt.consume(orgClaim, () -> {
halt(HttpStatus.SC_BAD_REQUEST, "Token does not specify the organization");
}, orgId -> {
if (!ChannelFactory.isAccessibleBy(channel, orgId)) {
halt(HttpStatus.SC_FORBIDDEN, "Token does not provide access to channel %s" + channel);
}
});
}
catch (InvalidJwtException | MalformedClaimException e) {
halt(HttpStatus.SC_FORBIDDEN,
String.format("Token is not valid to access %s in %s: %s", filename, channel, e.getMessage()));
}
}
private JsonWebToken getTokenCredential(Class<? extends TokenCredential> type) {
if (identity.isAnonymous()) {
return new NullJsonWebToken();
}
if (identity.getPrincipal() instanceof OidcJwtCallerPrincipal
&& ((OidcJwtCallerPrincipal) identity.getPrincipal()).getCredential().getClass() == type) {
return (JsonWebToken) identity.getPrincipal();
}
TokenCredential credential = identity.getCredential(type);
if (credential != null) {
if (credential instanceof AccessTokenCredential && ((AccessTokenCredential) credential).isOpaque()) {
throw new OIDCException("Opaque access token can not be converted to JsonWebToken");
}
JwtClaims jwtClaims;
try {
jwtClaims = new JwtConsumerBuilder()
.setSkipSignatureVerification()
.setSkipAllValidators()
.build().processToClaims(credential.getToken());
} catch (InvalidJwtException e) {
throw new OIDCException(e);
}
jwtClaims.setClaim(Claims.raw_token.name(), credential.getToken());
return new OidcJwtCallerPrincipal(jwtClaims, credential);
}
String tokenType = type == AccessTokenCredential.class ? "access" : "ID";
throw new OIDCException("Current identity is not associated with an " + tokenType + " token");
}
public static Token decypherToken(String token) {
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
.setRequireExpirationTime()
.setAllowedClockSkewInSeconds(30)
.setRequireSubject()
.setExpectedIssuer("Sanstorik")
.setExpectedAudience("User")
.setVerificationKey(key.getKey())
.setJwsAlgorithmConstraints(
new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST,
AlgorithmIdentifiers.RSA_USING_SHA256))
.build();
Token decypheredToken = null;
try
{
JwtClaims jwtClaims = jwtConsumer.processToClaims(token);
decypheredToken = new Token(token,
jwtClaims.getClaimValue(USERNAME_KEY).toString(),
jwtClaims.getClaimValue(PASSWORD_KEY).toString(),
Integer.valueOf(jwtClaims.getClaimValue(USERID_KEY).toString())
);
} catch (InvalidJwtException e) {
e.printStackTrace();
}
return decypheredToken;
}
@Test(groups = TCKConstants.TEST_GROUP_UTILS, expectedExceptions = {InvalidJwtException.class},
description = "Illustrate validation of iss")
public void testFailAlgorithm() throws Exception {
Set<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
invalidFields.add(TokenUtils.InvalidClaims.ALG);
String token = TokenUtils.encryptClaims("/Token1.json", invalidFields);
validateToken(token);
}
@Test(groups = TCKConstants.TEST_GROUP_UTILS, expectedExceptions = {InvalidJwtException.class},
description = "Illustrate validation of alg")
public void testFailIssuer() throws Exception {
Set<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
invalidFields.add(TokenUtils.InvalidClaims.ISSUER);
String token = TokenUtils.encryptClaims("/Token1.json", invalidFields);
validateToken(token);
}
@Test(groups = TCKConstants.TEST_GROUP_UTILS, expectedExceptions = {InvalidJwtException.class},
description = "Illustrate validation of encryptor")
public void testFailEncryption() throws Exception {
Set<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
invalidFields.add(TokenUtils.InvalidClaims.ENCRYPTOR);
String token = TokenUtils.encryptClaims("/Token1.json", invalidFields);
validateToken(token);
}
public static Map<String, Object> verifyJwt(String jwt) throws InvalidJwtException, MalformedClaimException {
Map<String, Object> user = null;
X509VerificationKeyResolver x509VerificationKeyResolver = new X509VerificationKeyResolver(certificate);
x509VerificationKeyResolver.setTryAllOnNoThumbHeader(true);
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
.setRequireExpirationTime() // the JWT must have an expiration time
.setAllowedClockSkewInSeconds((Integer) config.get(CLOCK_SKEW_IN_MINUTE)*60) // allow some leeway in validating time based claims to account for clock skew
.setRequireSubject() // the JWT must have a subject claim
.setExpectedIssuer(issuer)
.setExpectedAudience(audience)
.setVerificationKeyResolver(x509VerificationKeyResolver) // verify the signature with the certificates
.build(); // create the JwtConsumer instance
// Validate the JWT and process it to the Claims
JwtClaims claims = jwtConsumer.processToClaims(jwt);
if(claims != null) {
user = new HashMap<String, Object>();
user.put("userId", claims.getClaimValue("userId"));
user.put("clientId", claims.getClaimValue("clientId"));
List roles = claims.getStringListClaimValue("roles");
user.put("roles", roles);
Object host = claims.getClaimValue("host");
if(host != null) user.put("host", host);
}
return user;
}
@Test(groups = TCKConstants.TEST_GROUP_UTILS, expectedExceptions = {InvalidJwtException.class},
description = "Illustrate validation of exp that has just expired")
public void testFailJustExpired() throws Exception {
Map<String, Long> timeClaims = new HashMap<>();
// Set exp to 61 seconds in past
long exp = TokenUtils.currentTimeInSecs() - 61;
timeClaims.put(Claims.exp.name(), exp);
String token = TokenUtils.encryptClaims("/Token1.json", null, timeClaims);
validateToken(token);
}
@Test(groups = TCKConstants.TEST_GROUP_UTILS, expectedExceptions = {InvalidJwtException.class},
description = "Illustrate validation of alg")
public void testFailAlgorithm() throws Exception {
Set<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
invalidFields.add(TokenUtils.InvalidClaims.ALG);
String token = TokenUtils.signClaims("/Token1.json", SignatureAlgorithm.RS256, invalidFields);
validateToken(token);
}
@Test(groups = TCKConstants.TEST_GROUP_UTILS, expectedExceptions = {InvalidJwtException.class},
description = "Deprecated: Illustrate validation of alg")
public void testFailAlgorithmDeprecated() throws Exception {
Set<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
invalidFields.add(TokenUtils.InvalidClaims.ALG);
@SuppressWarnings("deprecation")
String token = TokenUtils.generateTokenString("/Token1.json", invalidFields);
validateToken(token);
}
@Test(groups = TCKConstants.TEST_GROUP_UTILS, expectedExceptions = {InvalidJwtException.class},
description = "Deprecated: Illustrate validation of issuer")
public void testFailIssuerDeprecated() throws Exception {
Set<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
invalidFields.add(TokenUtils.InvalidClaims.ISSUER);
@SuppressWarnings("deprecation")
String token = TokenUtils.generateTokenString("/Token1.json", invalidFields);
validateToken(token);
}
@Test(groups = TCKConstants.TEST_GROUP_UTILS, expectedExceptions = {InvalidJwtException.class},
description = "Illustrate validation of signer")
public void testFailSignature() throws Exception {
Set<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
invalidFields.add(TokenUtils.InvalidClaims.SIGNER);
String token = TokenUtils.signClaims("/Token1.json", SignatureAlgorithm.RS256, invalidFields);
validateToken(token);
}
@Test(groups = TCKConstants.TEST_GROUP_UTILS, expectedExceptions = {InvalidJwtException.class},
description = "Deprecated: Illustrate validation of signer")
public void testFailSignatureDeprecated() throws Exception {
Set<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
invalidFields.add(TokenUtils.InvalidClaims.SIGNER);
@SuppressWarnings("deprecation")
String token = TokenUtils.generateTokenString("/Token1.json", invalidFields);
validateToken(token);
}
protected JsonWebToken verify(JwtConsumerBuilder builder, String jwt) {
try {
JwtClaims claims = builder.build().processToClaims(jwt);
return new JsonWebToken(claims);
} catch (InvalidJwtException e) {
throw new SecurityException(e);
}
}
@Test(groups = TCKConstants.TEST_GROUP_UTILS, expectedExceptions = {InvalidJwtException.class},
description = "Deprecated: Illustrate validation of exp")
public void testFailExpiredDeprecated() throws Exception {
Map<String, Long> timeClaims = new HashMap<>();
Set<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
invalidFields.add(TokenUtils.InvalidClaims.EXP);
@SuppressWarnings("deprecation")
String token = TokenUtils.generateTokenString("/Token1.json", invalidFields, timeClaims);
validateToken(token);
}
@Test(groups = TCKConstants.TEST_GROUP_UTILS, expectedExceptions = {InvalidJwtException.class},
description = "Illustrate validation of exp that has just expired")
public void testFailJustExpired() throws Exception {
Map<String, Long> timeClaims = new HashMap<>();
// Set exp to 61 seconds in past
long exp = TokenUtils.currentTimeInSecs() - 61;
timeClaims.put(Claims.exp.name(), exp);
String token = TokenUtils.signClaims("/Token1.json", SignatureAlgorithm.RS256, null, timeClaims);
validateToken(token);
}
@Test(groups = TCKConstants.TEST_GROUP_UTILS, expectedExceptions = {InvalidJwtException.class},
description = "Deprecated: Illustrate validation of exp that has just expired")
public void testFailJustExpiredDeprecated() throws Exception {
Map<String, Long> timeClaims = new HashMap<>();
// Set exp to 61 seconds in past
long exp = TokenUtils.currentTimeInSecs() - 61;
timeClaims.put(Claims.exp.name(), exp);
@SuppressWarnings("deprecation")
String token = TokenUtils.generateTokenString("/Token1.json", null, timeClaims);
validateToken(token);
}
@Test(groups = TCKConstants.TEST_GROUP_UTILS, expectedExceptions = {InvalidJwtException.class},
description = "Illustrate validation failure if signed token is encrypted and no 'cty' header is set")
public void testEncryptSignedClaimsWithoutCty() throws Exception {
PrivateKey signingKey = TokenUtils.readPrivateKey("/privateKey.pem");
PublicKey encryptionKey = TokenUtils.readPublicKey("/publicKey.pem");
String token =
TokenUtils.signEncryptClaims(signingKey, "1", encryptionKey, "2", "/Token1.json", false);
validateToken(token, true);
}
/**
* Ensure a token is validated by the provider using the JWKS URL for the public key associated
* with the signer.
*
* @throws Exception
*/
@Test(expectedExceptions = {InvalidJwtException.class, BadJOSEException.class, JWTVerificationException.class})
public void testNoMatchingKID() throws Exception {
PrivateKey pk = loadPrivateKey();
String token = TokenUtils.generateTokenString(pk, "invalid-kid", "/Token1.json", null, null);
int expGracePeriodSecs = 60;
validateToken(token, new URL(endpoint), TEST_ISSUER, expGracePeriodSecs);
}