com.auth0.jwt.interfaces.Verification Java Examples

The following examples show how to use com.auth0.jwt.interfaces.Verification. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Auth0VerifierTest.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@Override
protected void validateToken(String token, RSAPublicKey publicKey, String issuer, int expGracePeriodSecs) throws Exception {
    Algorithm algorithm = Algorithm.RSA256(publicKey, null);
    Verification builder = JWT.require(algorithm)
        .withIssuer(issuer);
    if(expGracePeriodSecs > 0) {
        builder = builder.acceptLeeway(expGracePeriodSecs);
    }
    JWTVerifier verifier = builder.build();
    DecodedJWT jwt = verifier.verify(token);
}
 
Example #2
Source File: IlpOverHttpJwtEmitter.java    From quilt with Apache License 2.0 5 votes vote down vote up
/**
 * 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.");
  }
}
 
Example #3
Source File: IlpOverHttpJwtEmitter.java    From quilt with Apache License 2.0 5 votes vote down vote up
/**
 * 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.");
  }
}
 
Example #4
Source File: JWTVerifier.java    From java-jwt with MIT License 4 votes vote down vote up
@Override
public Verification withArrayClaim(String name, Long... items) throws IllegalArgumentException {
    assertNonNull(name);
    requireClaim(name, items);
    return this;
}
 
Example #5
Source File: JwtTokenExtractor.java    From botbuilder-java with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private CompletableFuture<ClaimsIdentity> validateToken(
    String token,
    String channelId,
    List<String> requiredEndorsements
) {
    return CompletableFuture.supplyAsync(() -> {
        DecodedJWT decodedJWT = JWT.decode(token);
        OpenIdMetadataKey key = this.openIdMetadata.getKey(decodedJWT.getKeyId());
        if (key == null) {
            return null;
        }

        Verification verification = JWT.require(Algorithm.RSA256(key.key, null))
            .acceptLeeway(tokenValidationParameters.clockSkew.getSeconds());
        try {
            verification.build().verify(token);

            // If specified, validate the signing certificate.
            if (
                tokenValidationParameters.validateIssuerSigningKey
                && key.certificateChain != null
                && key.certificateChain.size() > 0
            ) {
                // Note that decodeCertificate will return null if the cert could not
                // be decoded.  This would likely be the case if it were in an unexpected
                // encoding.  Going to err on the side of ignoring this check.
                // May want to reconsider this and throw on null cert.
                X509Certificate cert = decodeCertificate(key.certificateChain.get(0));
                if (cert != null && !isCertValid(cert)) {
                    throw new JWTVerificationException("Signing certificate is not valid");
                }
            }

            // Note: On the Emulator Code Path, the endorsements collection is null so the
            // validation code below won't run. This is normal.
            if (key.endorsements != null) {
                // Validate Channel / Token Endorsements. For this, the channelID present on the
                // Activity needs to be matched by an endorsement.
                boolean isEndorsed =
                    EndorsementsValidator.validate(channelId, key.endorsements);
                if (!isEndorsed) {
                    throw new AuthenticationException(
                        String.format(
                            "Could not validate endorsement for key: %s with endorsements: %s",
                            key.key.toString(), StringUtils.join(key.endorsements)
                        )
                    );
                }

                // Verify that additional endorsements are satisfied. If no additional
                // endorsements are expected, the requirement is satisfied as well
                boolean additionalEndorsementsSatisfied = requiredEndorsements.stream()
                    .allMatch(
                        (endorsement) -> EndorsementsValidator
                            .validate(endorsement, key.endorsements)
                    );
                if (!additionalEndorsementsSatisfied) {
                    throw new AuthenticationException(
                        String.format(
                            "Could not validate additional endorsement for key: %s with endorsements: %s",
                            key.key.toString(), StringUtils.join(requiredEndorsements)
                        )
                    );
                }
            }

            if (!this.allowedSigningAlgorithms.contains(decodedJWT.getAlgorithm())) {
                throw new AuthenticationException(
                    String.format(
                        "Could not validate algorithm for key: %s with algorithms: %s",
                        decodedJWT.getAlgorithm(), StringUtils.join(allowedSigningAlgorithms)
                    )
                );
            }

            return new ClaimsIdentity(decodedJWT);
        } catch (JWTVerificationException ex) {
            LOGGER.warn(ex.getMessage());
            throw new AuthenticationException(ex);
        }
    }, ExecutorFactory.getExecutor());
}
 
Example #6
Source File: JWTVerifier.java    From java-jwt with MIT License 4 votes vote down vote up
@Override
public Verification withArrayClaim(String name, Integer... items) throws IllegalArgumentException {
    assertNonNull(name);
    requireClaim(name, items);
    return this;
}
 
Example #7
Source File: JWTVerifier.java    From java-jwt with MIT License 4 votes vote down vote up
@Override
public Verification withArrayClaim(String name, String... items) throws IllegalArgumentException {
    assertNonNull(name);
    requireClaim(name, items);
    return this;
}
 
Example #8
Source File: JWTVerifier.java    From java-jwt with MIT License 4 votes vote down vote up
@Override
public Verification withClaim(String name, Date value) throws IllegalArgumentException {
    assertNonNull(name);
    requireClaim(name, value);
    return this;
}
 
Example #9
Source File: JWTVerifier.java    From java-jwt with MIT License 4 votes vote down vote up
@Override
public Verification withClaim(String name, String value) throws IllegalArgumentException {
    assertNonNull(name);
    requireClaim(name, value);
    return this;
}
 
Example #10
Source File: JWTVerifier.java    From java-jwt with MIT License 4 votes vote down vote up
@Override
public Verification withClaim(String name, Double value) throws IllegalArgumentException {
    assertNonNull(name);
    requireClaim(name, value);
    return this;
}
 
Example #11
Source File: JWTVerifier.java    From java-jwt with MIT License 4 votes vote down vote up
@Override
public Verification withClaim(String name, Long value) throws IllegalArgumentException {
    assertNonNull(name);
    requireClaim(name, value);
    return this;
}
 
Example #12
Source File: JWTVerifier.java    From java-jwt with MIT License 4 votes vote down vote up
@Override
public Verification withClaim(String name, Integer value) throws IllegalArgumentException {
    assertNonNull(name);
    requireClaim(name, value);
    return this;
}
 
Example #13
Source File: JWTVerifier.java    From java-jwt with MIT License 4 votes vote down vote up
@Override
public Verification withClaim(String name, Boolean value) throws IllegalArgumentException {
    assertNonNull(name);
    requireClaim(name, value);
    return this;
}
 
Example #14
Source File: JWTVerifier.java    From java-jwt with MIT License 4 votes vote down vote up
@Override
public Verification withJWTId(String jwtId) {
    requireClaim(PublicClaims.JWT_ID, jwtId);
    return this;
}
 
Example #15
Source File: JWTVerifier.java    From java-jwt with MIT License 4 votes vote down vote up
@Override
public Verification ignoreIssuedAt() {
    this.ignoreIssuedAt = true;
    return this;
}
 
Example #16
Source File: JWTVerifier.java    From java-jwt with MIT License 4 votes vote down vote up
@Override
public Verification acceptIssuedAt(long leeway) throws IllegalArgumentException {
    assertPositive(leeway);
    requireClaim(PublicClaims.ISSUED_AT, leeway);
    return this;
}
 
Example #17
Source File: JWTVerifier.java    From java-jwt with MIT License 4 votes vote down vote up
@Override
public Verification acceptNotBefore(long leeway) throws IllegalArgumentException {
    assertPositive(leeway);
    requireClaim(PublicClaims.NOT_BEFORE, leeway);
    return this;
}
 
Example #18
Source File: JWTVerifier.java    From java-jwt with MIT License 4 votes vote down vote up
@Override
public Verification acceptExpiresAt(long leeway) throws IllegalArgumentException {
    assertPositive(leeway);
    requireClaim(PublicClaims.EXPIRES_AT, leeway);
    return this;
}
 
Example #19
Source File: JWTVerifier.java    From java-jwt with MIT License 4 votes vote down vote up
@Override
public Verification acceptLeeway(long leeway) throws IllegalArgumentException {
    assertPositive(leeway);
    this.defaultLeeway = leeway;
    return this;
}
 
Example #20
Source File: JWTVerifier.java    From java-jwt with MIT License 4 votes vote down vote up
@Override
public Verification withAudience(String... audience) {
    requireClaim(PublicClaims.AUDIENCE, isNullOrEmpty(audience) ? null : Arrays.asList(audience));
    return this;
}
 
Example #21
Source File: JWTVerifier.java    From java-jwt with MIT License 4 votes vote down vote up
@Override
public Verification withSubject(String subject) {
    requireClaim(PublicClaims.SUBJECT, subject);
    return this;
}
 
Example #22
Source File: JWTVerifier.java    From java-jwt with MIT License 4 votes vote down vote up
@Override
public Verification withIssuer(String... issuer) {
    requireClaim(PublicClaims.ISSUER, isNullOrEmpty(issuer) ? null : Arrays.asList(issuer));
    return this;
}
 
Example #23
Source File: JwtVerify.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
@Override
public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {
	String token 		= getNamedStringParam(argStruct, "token", "" );
	String secret 		= getNamedStringParam(argStruct, "secret", "" );
	String issuer 		= getNamedStringParam(argStruct, "issuer", "" );
	String algorithm 	= getNamedStringParam(argStruct, "algorithm", "HMAC256" );
	
	Algorithm algo;
	Boolean verified = false;
	
	try {
		// Set the algorithm, default to HMAC256 if no match
		switch(algorithm) {
		case "HMAC384":
				algo = Algorithm.HMAC384(secret);
			break;
			
		case "HMAC512":
			algo = Algorithm.HMAC512(secret);
			break;
			
		default:
			algo = Algorithm.HMAC256(secret);
			break;
		}
	
		
		try {
			// If this doesn't throw an error, it's verified
			Verification verifier = JWT.require(algo);
		    
		    	verifier.withIssuer(issuer);
		    
		    @SuppressWarnings("unused")
			DecodedJWT jwt = verifier.build().verify(token);
		    
		    verified = true;
		} catch (JWTVerificationException exception){
			verified = false;
		}
	} catch (Exception e) {
		throwException(_session, e.getMessage());
	}
	
	return (verified == true) ? cfBooleanData.TRUE : cfBooleanData.FALSE;
}
 
Example #24
Source File: JWTVerifier.java    From java-jwt with MIT License 2 votes vote down vote up
/**
 * Initialize a JWTVerifier instance using the given Algorithm.
 *
 * @param algorithm the Algorithm to use on the JWT verification.
 * @return a JWTVerifier.Verification instance to configure.
 * @throws IllegalArgumentException if the provided algorithm is null.
 */
static Verification init(Algorithm algorithm) throws IllegalArgumentException {
    return new BaseVerification(algorithm);
}
 
Example #25
Source File: JWT.java    From java-jwt with MIT License 2 votes vote down vote up
/**
 * Returns a {@link JWTVerifier} builder with the algorithm to be used to validate token signature.
 *
 * @param algorithm that will be used to verify the token's signature.
 * @return {@link JWTVerifier} builder
 * @throws IllegalArgumentException if the provided algorithm is null.
 */
public static Verification require(Algorithm algorithm) {
    return JWTVerifier.init(algorithm);
}