Java Code Examples for com.nimbusds.jwt.JWTClaimsSet#getExpirationTime()

The following examples show how to use com.nimbusds.jwt.JWTClaimsSet#getExpirationTime() . 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: ScooldUtils.java    From scoold with Apache License 2.0 7 votes vote down vote up
public boolean isValidJWToken(String jwt) {
	try {
		String secret = Config.getConfigParam("app_secret_key", "");
		if (secret != null && jwt != null) {
			JWSVerifier verifier = new MACVerifier(secret);
			SignedJWT sjwt = SignedJWT.parse(jwt);
			if (sjwt.verify(verifier)) {
				Date referenceTime = new Date();
				JWTClaimsSet claims = sjwt.getJWTClaimsSet();

				Date expirationTime = claims.getExpirationTime();
				Date notBeforeTime = claims.getNotBeforeTime();
				String jti = claims.getJWTID();
				boolean expired = expirationTime != null && expirationTime.before(referenceTime);
				boolean notYetValid = notBeforeTime != null && notBeforeTime.after(referenceTime);
				boolean jtiRevoked = isApiKeyRevoked(jti, expired);
				return !(expired || notYetValid || jtiRevoked);
			}
		}
	} catch (JOSEException e) {
		logger.warn(null, e);
	} catch (ParseException ex) {
		logger.warn(null, ex);
	}
	return false;
}
 
Example 2
Source File: SecurityUtils.java    From para with Apache License 2.0 6 votes vote down vote up
/**
 * Validates a JWT token.
 * @param secret secret used for generating the token
 * @param jwt token to validate
 * @return true if token is valid
 */
public static boolean isValidJWToken(String secret, SignedJWT jwt) {
	try {
		if (secret != null && jwt != null) {
			JWSVerifier verifier = new MACVerifier(secret);
			if (jwt.verify(verifier)) {
				Date referenceTime = new Date();
				JWTClaimsSet claims = jwt.getJWTClaimsSet();

				Date expirationTime = claims.getExpirationTime();
				Date notBeforeTime = claims.getNotBeforeTime();
				boolean expired = expirationTime == null || expirationTime.before(referenceTime);
				boolean notYetValid = notBeforeTime != null && notBeforeTime.after(referenceTime);

				return !(expired || notYetValid);
			}
		}
	} catch (JOSEException e) {
		logger.warn(null, e);
	} catch (ParseException ex) {
		logger.warn(null, ex);
	}
	return false;
}
 
Example 3
Source File: KnoxService.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the jwt expiration.
 *
 * @param jwtToken knox jwt
 * @return whether this jwt is not expired
 * @throws ParseException if the payload of the jwt doesn't represent a valid json object and a jwt claims set
 */
private boolean validateExpiration(final SignedJWT jwtToken) throws ParseException {
    boolean valid = false;

    final JWTClaimsSet claimsSet = jwtToken.getJWTClaimsSet();
    if (claimsSet == null) {
        logger.error("Claims set is missing from Knox JWT.");
        return false;
    }

    final Date now = new Date();
    final Date expiration = claimsSet.getExpirationTime();

    // the token is not expired if the expiration isn't present or the expiration is after now
    if (expiration == null || now.before(expiration)) {
        valid = true;
    }

    if (!valid) {
        logger.error("The Knox JWT is expired.");
    }

    return valid;
}
 
Example 4
Source File: SelfContainedTokenValidator.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
private void validateExpiry(JWTClaimsSet jwtClaimsSet) throws TokenValidationFailureException {

        // Validating expiry is a part of signature validation.
        // validation.
        if (!CellStsConfiguration.getInstance().isSignatureValidationEnabled()) {
            log.debug("Issuer validation turned off.");
            return;
        }
        if (jwtClaimsSet.getExpirationTime().before(new Date(System.currentTimeMillis()))) {
            throw new TokenValidationFailureException("Token has expired. Expiry time: " + jwtClaimsSet
                    .getExpirationTime());
        }
        log.debug("Token life time is valid, expiry time: {}", jwtClaimsSet.getExpirationTime());
    }
 
Example 5
Source File: CellerySignedJWTValidator.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
private void validateMandatoryJWTClaims(JWTClaimsSet claimsSet) throws IdentityOAuth2Exception {

        String subject = claimsSet.getSubject();
        List<String> audience = claimsSet.getAudience();
        String jti = claimsSet.getJWTID();
        if (StringUtils.isEmpty(claimsSet.getIssuer()) || StringUtils.isEmpty(subject) ||
                claimsSet.getExpirationTime() == null || audience == null || jti == null) {
            throw new IdentityOAuth2Exception("Mandatory fields(Issuer, Subject, Expiration time, jtl or Audience) " +
                    "are empty in the given Token.");
        }
    }
 
Example 6
Source File: JWTValidatorImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
protected boolean validateTokenExpiry(JWTClaimsSet jwtClaimsSet) {

        long timestampSkew =
                ServiceReferenceHolder.getInstance().getOauthServerConfiguration().getTimeStampSkewInSeconds();
        Date now = new Date();
        Date exp = jwtClaimsSet.getExpirationTime();
        return exp == null || DateUtils.isAfter(exp, now, timestampSkew);
    }
 
Example 7
Source File: DefaultConsentReferencePolicy.java    From XS2A-Sandbox with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("PMD")
private ConsentReference verifyParseJWT(String encryptedConsentId, String authorizationId, String cookieString, boolean strict) {
    Date refTime = new Date();
    try {
        SignedJWT jwt = SignedJWT.parse(cookieString);
        JWTClaimsSet jwtClaimsSet = jwt.getJWTClaimsSet();

        // Validate xsrf
        Object authorizationIdClaim = jwtClaimsSet.getClaim(AUTH_ID_JWT_CLAIM_NAME);
        if (strict && authorizationIdClaim == null) {
            throw invalidConsent(String.format("Wrong jwt. CSRF allert. Missing claim %s for jwt with redirectId %s", AUTH_ID_JWT_CLAIM_NAME, jwtClaimsSet.getClaim(REDIRECT_ID_JWT_CLAIM_NAME)));
        }

        if (authorizationIdClaim != null && !StringUtils.equalsIgnoreCase(authorizationIdClaim.toString(), authorizationId)) {
            throw invalidConsent(String.format("Wrong jwt. CSRF allert. Wrong %s for token with redirectId %s", AUTH_ID_JWT_CLAIM_NAME, jwtClaimsSet.getClaim(REDIRECT_ID_JWT_CLAIM_NAME)));
        }

        Object encryptedConsentIdClaim = jwtClaimsSet.getClaim(ENC_CONSENT_ID_JWT_CLAIM_NAME);
        if (encryptedConsentIdClaim == null || !StringUtils.equalsIgnoreCase(encryptedConsentIdClaim.toString(), encryptedConsentId)) {
            throw invalidConsent(String.format("Wrong jwt. CSRF allert. Wrong %s for token with redirectId %s", ENC_CONSENT_ID_JWT_CLAIM_NAME, jwtClaimsSet.getClaim(REDIRECT_ID_JWT_CLAIM_NAME)));
        }

        JWSHeader header = jwt.getHeader();
        // CHeck algorithm
        if (!JWSAlgorithm.HS256.equals(header.getAlgorithm())) {
            throw invalidConsent(String.format("Wrong jws algo for token with subject : %s", jwtClaimsSet.getSubject()));
        }

        // CHeck expiration
        if (jwtClaimsSet.getExpirationTime() == null || jwtClaimsSet.getExpirationTime().before(refTime)) {
            throw invalidConsent(String.format(
                "Token with subject %s is expired at %s and reference time is %s : ", jwtClaimsSet.getSubject(),
                jwtClaimsSet.getExpirationTime(), refTime));
        }

        // check signature.
        boolean verified = jwt.verify(new MACVerifier(hmacSecret));
        if (!verified) {
            throw invalidConsent(String.format("Could not verify signature of token with subject %s: ", jwtClaimsSet.getSubject()));
        }

        return consentReference(encryptedConsentId, authorizationId, jwtClaimsSet);

    } catch (ParseException | JOSEException e) {
        // If we can not parse the token, we log the error and return false.
        throw invalidConsent(e.getMessage());
    }
}
 
Example 8
Source File: JwtLoginService.java    From cruise-control with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private boolean validateExpiration(JWTClaimsSet claimsSet) {
  Date expires = claimsSet.getExpirationTime();
  return expires == null || _clock.instant().isBefore(expires.toInstant());
}