Java Code Examples for com.nimbusds.jwt.SignedJWT#verify()

The following examples show how to use com.nimbusds.jwt.SignedJWT#verify() . 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: KnoxService.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the jwt signature.
 *
 * @param jwtToken knox jwt
 * @return whether this jwt signature is valid
 * @throws JOSEException if the jws object couldn't be verified
 */
private boolean validateSignature(final SignedJWT jwtToken) throws JOSEException {
    boolean valid = false;

    // ensure the token is signed
    if (JWSObject.State.SIGNED.equals(jwtToken.getState())) {

        // ensure the signature is present
        if (jwtToken.getSignature() != null) {

            // verify the token
            valid = jwtToken.verify(verifier);
        }
    }

    if (!valid) {
        logger.error("The Knox JWT has an invalid signature.");
    }

    return valid;
}
 
Example 3
Source File: MACVerifierExtendedTest.java    From shiro-jwt with MIT License 6 votes vote down vote up
@Test
public void invalidTokenExpirationTime() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(), new Date());

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertFalse("Must be invalid", signed.verify(verifier));
}
 
Example 4
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 5
Source File: TokenProviderUtility.java    From Insights with Apache License 2.0 6 votes vote down vote up
/**
 * used to delete token from cache
 * 
 * @param csrfauthToken
 * @return
 * @throws Exception
 */
public boolean deleteToken(String csrfauthToken) throws Exception {
	Boolean isTokenRemoved = Boolean.FALSE;
	try {
		SignedJWT signedJWT = SignedJWT.parse(csrfauthToken);
		JWSVerifier verifier = new MACVerifier(signingKey);
		Boolean isVerify = signedJWT.verify(verifier);

		String id = signedJWT.getJWTClaimsSet().getJWTID();
		String key = TokenProviderUtility.tokenCache.get(id);
		if (key != null && isVerify) {
			TokenProviderUtility.tokenCache.remove(id);
			isTokenRemoved = Boolean.TRUE;
		}
	} catch (Exception e) {
		log.error(e);
		log.error(" Exception while deleting token {}", e.getMessage());
	}
	return isTokenRemoved;
}
 
Example 6
Source File: OAuthHandler.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
private String extractAppIdFromIdToken(String token) {
    String appId = null;
    KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID);
    try {
        keyStoreManager.getDefaultPrimaryCertificate();
        JWSVerifier verifier =
                new RSASSAVerifier((RSAPublicKey) keyStoreManager.getDefaultPublicKey());
        SignedJWT jwsObject = SignedJWT.parse(token);
        if (jwsObject.verify(verifier)) {
            appId = jwsObject.getJWTClaimsSet().getStringClaim("appId");
        }

    } catch (Exception e) {
        String message = "Could not extract application id from id token";
        log.error(message, e);
    }
    return appId;
}
 
Example 7
Source File: JWTAuthenticationHandler.java    From registry with Apache License 2.0 6 votes vote down vote up
/**
 * Verify the signature of the JWT token in this method. This method depends
 * on the public key that was established during init based upon the
 * provisioned public key. Override this method in subclasses in order to
 * customize the signature verification behavior.
 *
 * @param jwtToken the token that contains the signature to be validated
 * @return valid true if signature verifies successfully; false otherwise
 */
protected boolean validateSignature(SignedJWT jwtToken) {
    boolean valid = false;
    if (JWSObject.State.SIGNED == jwtToken.getState()) {
        LOG.debug("JWT token is in a SIGNED state");
        if (jwtToken.getSignature() != null) {
            LOG.debug("JWT token signature is not null");
            try {
                JWSVerifier verifier = new RSASSAVerifier(publicKey);
                if (jwtToken.verify(verifier)) {
                    valid = true;
                    LOG.debug("JWT token has been successfully verified");
                } else {
                    LOG.warn("JWT signature verification failed.");
                }
            } catch (JOSEException je) {
                LOG.warn("Error while validating signature", je);
            }
        }
    }
    return valid;
}
 
Example 8
Source File: JWTSecurityInterceptor.java    From msf4j with Apache License 2.0 6 votes vote down vote up
private boolean verifySignature(String jwt) {
    try {
        SignedJWT signedJWT = SignedJWT.parse(jwt);
        if (new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime())) {
            JWSVerifier verifier =
                    new RSASSAVerifier((RSAPublicKey) getPublicKey(KEYSTORE, KEYSTORE_PASSWORD, ALIAS));
            return signedJWT.verify(verifier);
        } else {
            log.info("Token has expired");
        }
    } catch (ParseException | IOException | KeyStoreException | CertificateException |
            NoSuchAlgorithmException | UnrecoverableKeyException | JOSEException e) {
        log.error("Error occurred while JWT signature verification. JWT=" + jwt, e);
    }
    return false;
}
 
Example 9
Source File: JWTUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Verify the JWT token signature.
 *
 * @param jwt SignedJwt Token
 * @param publicKey      public certificate
 * @return whether the signature is verified or or not
 */
public static boolean verifyTokenSignature(SignedJWT jwt, RSAPublicKey publicKey) {

    JWSAlgorithm algorithm = jwt.getHeader().getAlgorithm();
    if ((JWSAlgorithm.RS256.equals(algorithm) || JWSAlgorithm.RS512.equals(algorithm) ||
            JWSAlgorithm.RS384.equals(algorithm))) {
        try {
            JWSVerifier jwsVerifier = new RSASSAVerifier(publicKey);
            return jwt.verify(jwsVerifier);
        } catch (JOSEException e) {
            log.error("Error while verifying JWT signature", e);
            return false;
        }
    } else {
        log.error("Public key is not a RSA");
        return false;
    }
}
 
Example 10
Source File: GatewayUtils.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Verify the JWT token signature.
 *
 * @param jwt SignedJwt Token
 * @param publicKey      public certificate
 * @return whether the signature is verified or or not
 * @throws APISecurityException in case of signature verification failure
 */
public static boolean verifyTokenSignature(SignedJWT jwt, RSAPublicKey publicKey) throws APISecurityException {

    JWSAlgorithm algorithm = jwt.getHeader().getAlgorithm();
    if (algorithm != null && (JWSAlgorithm.RS256.equals(algorithm) || JWSAlgorithm.RS512.equals(algorithm) ||
            JWSAlgorithm.RS384.equals(algorithm))) {
        try {
            JWSVerifier jwsVerifier = new RSASSAVerifier(publicKey);
            return jwt.verify(jwsVerifier);
        } catch (JOSEException e) {
            log.error("Error while verifying JWT signature");
            throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS,
                    APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE, e);
        }
    } else {
        log.error("Public key is not a RSA");
        throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
                APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
    }
}
 
Example 11
Source File: DefaultJwtSigningAndValidationService.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validateSignature(SignedJWT jwt) {

	for (JWSVerifier verifier : verifiers.values()) {
		try {
			if (jwt.verify(verifier)) {
				return true;
			}
		} catch (JOSEException e) {

			logger.error("Failed to validate signature, error was: ", e);
		}
	}
	return false;
}
 
Example 12
Source File: KnoxSSOAuthenticationFilter.java    From metron with Apache License 2.0 5 votes vote down vote up
/**
 * Verify the signature of the JWT token in this method. This method depends on
 * the public key that was established during init based upon the provisioned
 * public key. Override this method in subclasses in order to customize the
 * signature verification behavior.
 *
 * @param jwtToken The token that contains the signature to be validated.
 * @return valid true if signature verifies successfully; false otherwise
 */
protected boolean validateSignature(SignedJWT jwtToken) {
  // Verify the token signature algorithm was as expected
  String receivedSigAlg = jwtToken.getHeader().getAlgorithm().getName();

  if (!receivedSigAlg.equals(JWSAlgorithm.RS256.getName())) {
    return false;
  }

  // Verify the token has been properly signed
  if (JWSObject.State.SIGNED == jwtToken.getState()) {
    LOG.debug("SSO token is in a SIGNED state");
    if (jwtToken.getSignature() != null) {
      LOG.debug("SSO token signature is not null");
      try {
        JWSVerifier verifier = getRSASSAVerifier();
        if (jwtToken.verify(verifier)) {
          LOG.debug("SSO token has been successfully verified");
          return true;
        } else {
          LOG.warn("SSO signature verification failed. Please check the public key.");
        }
      } catch (Exception e) {
        LOG.warn("Error while validating signature", e);
      }
    }
  }
  return false;
}
 
Example 13
Source File: AtlasKnoxSSOAuthenticationFilter.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
/**
 * Verify the signature of the JWT token in this method. This method depends
 * on the public key that was established during init based upon the
 * provisioned public key. Override this method in subclasses in order to
 * customize the signature verification behavior.
 *
 * @param jwtToken the token that contains the signature to be validated
 * @return valid true if signature verifies successfully; false otherwise
 */
protected boolean validateSignature(SignedJWT jwtToken) {
    boolean valid = false;
    if (JWSObject.State.SIGNED == jwtToken.getState()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("SSO token is in a SIGNED state");
        }
        if (jwtToken.getSignature() != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("SSO token signature is not null");
            }
            try {
                if (verifier != null && jwtToken.verify(verifier)) {
                    valid = true;
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("SSO token has been successfully verified");
                    }
                } else {
                    LOG.warn("SSO signature verification failed.Please check the public key");
                }
            } catch (JOSEException je) {
                LOG.warn("Error while validating signature", je);
            } catch (Exception e) {
                LOG.warn("Error while validating signature", e);
            }
        }
    }
    return valid;
}
 
Example 14
Source File: JWSServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValidSignature(JWT jwt, JWK jwk) {
    try {
        SignedJWT signedJwt = (SignedJWT)jwt;
        return signedJwt.verify(this.verifier(jwk));
    } catch (ClassCastException | JOSEException ex) {
        LOGGER.error(ex.getMessage(),ex);
        return false;
    }
}
 
Example 15
Source File: TokenProviderUtility.java    From Insights with Apache License 2.0 5 votes vote down vote up
/**
 * Used to verify received token with cached token
 * 
 * @param token
 * @return
 * @throws AuthorizationServiceException
 * @throws AuthenticationCredentialsNotFoundException
 * @throws AccountExpiredException
 * @throws InsightsCustomException
 */
public boolean verifyToken(String token) throws AuthorizationServiceException,
		AuthenticationCredentialsNotFoundException, AccountExpiredException, InsightsCustomException {
	boolean isVerify = Boolean.FALSE;
	boolean isTokenExistsInCache = Boolean.FALSE;
	boolean validateTokenDate = Boolean.FALSE;
	//log.debug(" In verifyToken ");
	try {
		String authToken = ValidationUtils.cleanXSS(token);
		if (authToken == null || authToken.isEmpty()) {
			log.error("authToken is null or empty");
			throw new InsightsCustomException("authToken is null or empty");
		}

		// parse the JWS and verify its HMAC
		SignedJWT signedJWT = SignedJWT.parse(authToken);
		JWSVerifier verifier = new MACVerifier(signingKey);
		isVerify = signedJWT.verify(verifier);

		String id = signedJWT.getJWTClaimsSet().getJWTID();
		String tokenValueFromCache = null;
		if (TokenProviderUtility.tokenCache != null) {
			tokenValueFromCache = TokenProviderUtility.tokenCache.get(id);
		} else {
			log.error("cache is not initilize properly");
		}

		if (tokenValueFromCache == null) {
			log.debug("No token found in cache");
		} else if (tokenValueFromCache.equalsIgnoreCase(authToken)) {
			//log.debug("Token value matched in cache === ");
			isTokenExistsInCache = Boolean.TRUE;
		} else {
			log.error("Token value not matched in cache=== ");
		}

		//log.debug("alice  after " + signedJWT.getJWTClaimsSet().getSubject());
		//log.debug("cognizant.com  " + signedJWT.getJWTClaimsSet().getIssuer());
		//log.debug("Exceperation Time after  " + signedJWT.getJWTClaimsSet().getExpirationTime());
		log.debug("Check date of token with current date {} ",
				new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime()));//after
		validateTokenDate = new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime());//after

	} catch (Exception e) {
		log.error(e);
		log.error(" Exception while validating token {} ", e.getMessage());
		isVerify = Boolean.FALSE;
		throw new InsightsCustomException("Exception while varifing token ==== " + e.getMessage());
	}

	if (!isVerify) {
		log.debug("Token signuture not match ");
		isVerify = Boolean.FALSE;
		throw new AuthorizationServiceException("Token signuture not match");
	} else if (!isTokenExistsInCache) {
		log.error("Token Not matched ");
		isVerify = Boolean.FALSE;
		throw new AuthenticationCredentialsNotFoundException("Token not found in cache");
	} else if (!validateTokenDate) {
		isVerify = Boolean.FALSE;
		throw new AccountExpiredException("Token Expire");
	} else {
		log.debug("Token verified sucessfully ==== ");
		isVerify = Boolean.TRUE;
	}

	log.debug(" is Token Verify  ====  {} ", isVerify);

	return isVerify;
}
 
Example 16
Source File: AtlasKnoxSSOAuthenticationFilter.java    From atlas with Apache License 2.0 5 votes vote down vote up
/**
 * Verify the signature of the JWT token in this method. This method depends
 * on the public key that was established during init based upon the
 * provisioned public key. Override this method in subclasses in order to
 * customize the signature verification behavior.
 *
 * @param jwtToken the token that contains the signature to be validated
 * @return valid true if signature verifies successfully; false otherwise
 */
protected boolean validateSignature(SignedJWT jwtToken) {
    boolean valid = false;
    if (JWSObject.State.SIGNED == jwtToken.getState()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("SSO token is in a SIGNED state");
        }
        if (jwtToken.getSignature() != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("SSO token signature is not null");
            }
            try {
                if (verifier != null && jwtToken.verify(verifier)) {
                    valid = true;
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("SSO token has been successfully verified");
                    }
                } else {
                    LOG.warn("SSO signature verification failed.Please check the public key");
                }
            } catch (JOSEException je) {
                LOG.warn("Error while validating signature", je);
            } catch (Exception e) {
                LOG.warn("Error while validating signature", e);
            }
        }
    }
    return valid;
}
 
Example 17
Source File: JwtLoginService.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private boolean validateSignature(SignedJWT jwtToken) {
  if (JWSObject.State.SIGNED != jwtToken.getState() || jwtToken.getSignature() == null) {
    return false;
  }
  JWSVerifier verifier = new RSASSAVerifier(_publicKey);
  try {
    return jwtToken.verify(verifier);
  } catch (JOSEException e) {
    JWT_LOGGER.warn("Couldn't verify the signature of a token", e);
    return false;
  }
}
 
Example 18
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 19
Source File: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
private boolean processOCSPBypassSSD(String ocsp_ssd, OcspResponseCacheKey cid, String hostname)
{
  try
  {
    /*
     * Get unverified part of the JWT to extract issuer.
     */
    SignedJWT jwt_unverified = SignedJWT.parse(ocsp_ssd);
    String jwt_issuer = (String) jwt_unverified.getHeader().getCustomParam("ssd_iss");
    String ssd_pubKey;

    if (jwt_issuer.equals("dep1"))
    {
      ssd_pubKey = ssdManager.getPubKey("dep1");
    }
    else
    {
      ssd_pubKey = ssdManager.getPubKey("dep2");
    }

    String publicKeyContent =
        ssd_pubKey.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "");
    KeyFactory kf = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyContent));
    RSAPublicKey rsaPubKey = (RSAPublicKey) kf.generatePublic(keySpecX509);

    /*
     * Verify signature of the JWT Token
     * Verify time validity of the JWT Token (API does not do this)
     */
    SignedJWT jwt_token_verified = SignedJWT.parse(ocsp_ssd);
    JWSVerifier jwsVerifier = new RSASSAVerifier(rsaPubKey);
    if (jwt_token_verified.verify(jwsVerifier))
    {
      String sfc_endpoint = jwt_token_verified.getJWTClaimsSet().getStringClaim("sfcEndpoint");
      String jwt_certid = jwt_token_verified.getJWTClaimsSet().getStringClaim("certId");
      Date jwt_nbf = jwt_token_verified.getJWTClaimsSet().getNotBeforeTime();
      Date jwt_exp = jwt_token_verified.getJWTClaimsSet().getExpirationTime();

      long current_ts = System.currentTimeMillis();
      if (current_ts < jwt_exp.getTime() && current_ts >= jwt_nbf.getTime())
      {
        if (!sfc_endpoint.equals("*"))
        {
          /*
           * In case there are multiple hostnames
           * associated to the same account. The
           * code expects a space separated list
           * of all hostnames associated with this
           * account in sfcEndpoint field
           */

          String[] splitString = sfc_endpoint.split("\\s+");

          for (String s : splitString)
          {
            if (s.equals(hostname))
            {
              return true;
            }
          }
          return false;
        }
        /*
         * No In Band token can have > 7 days validity
         */
        if (jwt_exp.getTime() - jwt_nbf.getTime() > (7 * 24 * 60 * 60 * 1000))
        {
          return false;
        }
        byte[] jwt_certid_dec = Base64.decodeBase64(jwt_certid);
        DLSequence jwt_rawCertId = (DLSequence) ASN1ObjectIdentifier.fromByteArray(jwt_certid_dec);
        ASN1Encodable[] jwt_rawCertIdArray = jwt_rawCertId.toArray();
        byte[] issuerNameHashDer = ((DEROctetString) jwt_rawCertIdArray[1]).getEncoded();
        byte[] issuerKeyHashDer = ((DEROctetString) jwt_rawCertIdArray[2]).getEncoded();
        BigInteger serialNumber = ((ASN1Integer) jwt_rawCertIdArray[3]).getValue();

        OcspResponseCacheKey k = new OcspResponseCacheKey(
            issuerNameHashDer, issuerKeyHashDer, serialNumber);

        if (k.equals(cid))
        {
          LOGGER.debug("Found a Signed OCSP Bypass SSD for ceri id {}", cid);
          return true;
        }
        LOGGER.debug("Found invalid OCSP bypass for cert id {}", cid);
        return false;
      }
    }
    return false;
  }
  catch (Throwable ex)
  {
    LOGGER.debug("Failed to parse JWT Token, aborting");
    return false;
  }
}
 
Example 20
Source File: RefreshTokenGrantTypeHandler.java    From tutorials with MIT License 4 votes vote down vote up
@Override
public JsonObject createAccessToken(String clientId, MultivaluedMap<String, String> params) throws Exception {
    String refreshToken = params.getFirst("refresh_token");
    if (refreshToken == null || "".equals(refreshToken)) {
        throw new WebApplicationException("invalid_grant");
    }

    //Decode refresh token
    SignedJWT signedRefreshToken = SignedJWT.parse(refreshToken);
    JWSVerifier verifier = getJWSVerifier();

    if (!signedRefreshToken.verify(verifier)) {
        throw new WebApplicationException("Invalid refresh token.");
    }
    if (!(new Date().before(signedRefreshToken.getJWTClaimsSet().getExpirationTime()))) {
        throw new WebApplicationException("Refresh token expired.");
    }
    String refreshTokenClientId = signedRefreshToken.getJWTClaimsSet().getStringClaim("client_id");
    if (!clientId.equals(refreshTokenClientId)) {
        throw new WebApplicationException("Invalid client_id.");
    }

    //At this point, the refresh token is valid and not yet expired
    //So create a new access token from it.
    String subject = signedRefreshToken.getJWTClaimsSet().getSubject();
    String approvedScopes = signedRefreshToken.getJWTClaimsSet().getStringClaim("scope");

    String requestedScopes = params.getFirst("scope");
    if (requestedScopes != null && !requestedScopes.isEmpty()) {
        Set<String> rScopes = new HashSet(Arrays.asList(requestedScopes.split(" ")));
        Set<String> aScopes = new HashSet(Arrays.asList(approvedScopes.split(" ")));
        if (!aScopes.containsAll(rScopes)) {
            JsonObject error = Json.createObjectBuilder()
                    .add("error", "Invalid_request")
                    .add("error_description", "Requested scopes should be a subset of the original scopes.")
                    .build();
            Response response = Response.status(Response.Status.BAD_REQUEST).entity(error).build();
            throw new WebApplicationException(response);
        }
    } else {
        requestedScopes = approvedScopes;
    }

    String accessToken = getAccessToken(clientId, subject, requestedScopes);
    return Json.createObjectBuilder()
            .add("token_type", "Bearer")
            .add("access_token", accessToken)
            .add("expires_in", expiresInMin * 60)
            .add("scope", requestedScopes)
            .add("refresh_token", refreshToken)
            .build();
}