com.nimbusds.jose.crypto.RSASSAVerifier Java Examples

The following examples show how to use com.nimbusds.jose.crypto.RSASSAVerifier. 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: KnoxJwtRealm.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
protected boolean validateSignature(SignedJWT jwtToken) {
  boolean valid = false;
  if (JWSObject.State.SIGNED == jwtToken.getState()) {
    if (jwtToken.getSignature() != null) {
      try {
        RSAPublicKey publicKey = parseRSAPublicKey(publicKeyPath);
        JWSVerifier verifier = new RSASSAVerifier(publicKey);
        if (verifier != null && jwtToken.verify(verifier)) {
          valid = true;
        }
      } catch (Exception e) {
        LOGGER.info("Exception in validateSignature", e);
      }
    }
  }
  return valid;
}
 
Example #2
Source File: DefaultTokenAuthorityService.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public boolean verifyToken(JWT token, RSAPublicKey publicKey)
    throws TokenServiceException {
  boolean rc;
  PublicKey key;
  try {
    if (publicKey == null) {
      key = ks.getSigningKeystore().getCertificate(getSigningKeyAlias()).getPublicKey();
    }
    else {
      key = publicKey;
    }
    JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) key);
    // TODO: interrogate the token for issuer claim in order to determine the public key to use for verification
    // consider jwk for specifying the key too
    rc = token.verify(verifier);
  } catch (KeyStoreException | KeystoreServiceException e) {
    throw new TokenServiceException("Cannot verify token.", e);
  }
  return rc;
}
 
Example #3
Source File: JWTTokenTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Test
public void testTokenSignature() throws Exception {
  String[] claims = new String[4];
  claims[0] = "KNOXSSO";
  claims[1] = "[email protected]";
  claims[2] = "https://login.example.com";
  claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
  JWT token = new JWTToken("RS256", claims);

  assertEquals("KNOXSSO", token.getIssuer());
  assertEquals("[email protected]", token.getSubject());
  assertEquals("https://login.example.com", token.getAudience());

  // Sign the token
  JWSSigner signer = new RSASSASigner(privateKey);
  token.sign(signer);
  assertTrue(token.getSignaturePayload().length > 0);

  // Verify the signature
  JWSVerifier verifier = new RSASSAVerifier(publicKey);
  assertTrue(token.verify(verifier));
}
 
Example #4
Source File: JWTTokenTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Test
public void testTokenSignatureRS512() throws Exception {
  String[] claims = new String[4];
  claims[0] = "KNOXSSO";
  claims[1] = "[email protected]";
  claims[2] = "https://login.example.com";
  claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
  JWT token = new JWTToken(JWSAlgorithm.RS512.getName(), claims);

  assertEquals("KNOXSSO", token.getIssuer());
  assertEquals("[email protected]", token.getSubject());
  assertEquals("https://login.example.com", token.getAudience());
  assertTrue(token.getHeader().contains(JWSAlgorithm.RS512.getName()));

  // Sign the token
  JWSSigner signer = new RSASSASigner(privateKey);
  token.sign(signer);
  assertTrue(token.getSignaturePayload().length > 0);

  // Verify the signature
  JWSVerifier verifier = new RSASSAVerifier(publicKey);
  assertTrue(token.verify(verifier));
}
 
Example #5
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 #6
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 #7
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 #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: KnoxService.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new KnoxService.
 *
 * @param configuration          knox configuration
 */
public KnoxService(final KnoxConfiguration configuration) {
    this.configuration = configuration;

    // if knox sso support is enabled, validate the configuration
    if (configuration.isKnoxEnabled()) {
        // ensure the url is provided
        knoxUrl = configuration.getKnoxUrl();
        if (StringUtils.isBlank(knoxUrl)) {
            throw new RuntimeException("Knox URL is required when Apache Knox SSO support is enabled.");
        }

        // ensure the cookie name is set
        if (StringUtils.isBlank(configuration.getKnoxCookieName())) {
            throw new RuntimeException("Knox Cookie Name is required when Apache Knox SSO support is enabled.");
        }

        // create the verifier
        verifier = new RSASSAVerifier(configuration.getKnoxPublicKey());

        // get the audience
        audiences = configuration.getAudiences();
    }
}
 
Example #10
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 #11
Source File: TokenUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static boolean verifyTokenRSA( PublicKey pKey, String token )
{
    try
    {
        Payload pl = new Payload( token );
        JWSObject jwsObject = new JWSObject( new JWSHeader( JWSAlgorithm.RS256 ), pl );
        JWSVerifier verifier = new RSASSAVerifier( ( RSAPublicKey ) pKey );

        return jwsObject.verify( verifier );
    }
    catch ( JOSEException e )
    {
        LOG.warn( "Error verifying RSA token", e.getMessage() );

        return false;
    }
}
 
Example #12
Source File: AtlasKnoxSSOAuthenticationFilter.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
private void setJwtProperties() {
    if (jwtProperties != null) {
        authenticationProviderUrl = jwtProperties.getAuthenticationProviderUrl();
        publicKey = jwtProperties.getPublicKey();
        cookieName = jwtProperties.getCookieName();
        originalUrlQueryParam = jwtProperties.getOriginalUrlQueryParam();
        if (publicKey != null) {
            verifier = new RSASSAVerifier(publicKey);
        }
    }
}
 
Example #13
Source File: RangerSSOAuthenticationFilter.java    From ranger 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 {
				JWSVerifier verifier = new RSASSAVerifier(publicKey);
				if (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);
			}
		}

		// Now check that the signature algorithm was as expected
		if (valid) {
		  String receivedSigAlg = jwtToken.getHeader().getAlgorithm().getName();
		  if (!receivedSigAlg.equals(jwtProperties.getExpectedSigAlg())) {
		    valid = false;
		  }
		}
	}
	return valid;
}
 
Example #14
Source File: JWSServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private JWSVerifier from(RSAKey rsaKey) {
    try {
        byte[] modulus = Base64.getUrlDecoder().decode(rsaKey.getN());
        byte[] exponent = Base64.getUrlDecoder().decode(rsaKey.getE());
        RSAPublicKeySpec spec = new RSAPublicKeySpec(new BigInteger(1,modulus), new BigInteger(1,exponent));
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return new RSASSAVerifier((RSAPublicKey) factory.generatePublic(spec));
    }
    catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        LOGGER.error("Unable to build Signature Verifier from RSA key",ex);
        throw new IllegalArgumentException("Signature is using and unknown/not managed key");
    }
}
 
Example #15
Source File: JWTUtils.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public static boolean validate(JWToken jwToken, String subject, String keyId, X509Certificate certificate) throws ParseException, JOSEException {
    RSASSAVerifier verifier = new RSASSAVerifier((RSAPublicKey)certificate.getPublicKey());
    SignedJWT signedJWT = SignedJWT.parse(jwToken.getToken());
    boolean verified = signedJWT.verify(verifier);
    String sub = signedJWT.getJWTClaimsSet().getSubject();
    String kid = signedJWT.getHeader().getKeyID();
    Date expires = signedJWT.getJWTClaimsSet().getExpirationTime();
    Date nowDate = new Date();
    boolean expired = nowDate.getTime() > expires.getTime();
    return verified && subject.equals(sub) && keyId.equals(kid) && !expired;
}
 
Example #16
Source File: AtlasKnoxSSOAuthenticationFilter.java    From atlas with Apache License 2.0 5 votes vote down vote up
private void setJwtProperties() {
    if (jwtProperties != null) {
        authenticationProviderUrl = jwtProperties.getAuthenticationProviderUrl();
        publicKey = jwtProperties.getPublicKey();
        cookieName = jwtProperties.getCookieName();
        originalUrlQueryParam = jwtProperties.getOriginalUrlQueryParam();
        if (publicKey != null) {
            verifier = new RSASSAVerifier(publicKey);
        }
    }
}
 
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: AbstractGrantTypeHandler.java    From tutorials with MIT License 4 votes vote down vote up
protected JWSVerifier getJWSVerifier() throws Exception {
    String verificationkey = config.getValue("verificationkey", String.class);
    String pemEncodedRSAPublicKey = PEMKeyUtils.readKeyAsString(verificationkey);
    RSAKey rsaPublicKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPublicKey);
    return new RSASSAVerifier(rsaPublicKey);
}
 
Example #19
Source File: AbstractJWTFilterTest.java    From knox with Apache License 2.0 4 votes vote down vote up
@Override
public boolean verifyToken(JWT token, RSAPublicKey publicKey) {
  JWSVerifier verifier = new RSASSAVerifier(publicKey);
  return token.verify(verifier);
}
 
Example #20
Source File: AbstractJWTFilterTest.java    From knox with Apache License 2.0 4 votes vote down vote up
@Override
public boolean verifyToken(JWT token) {
  JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) verifyingKey);
  return token.verify(verifier);
}
 
Example #21
Source File: TokenServiceResourceTest.java    From knox with Apache License 2.0 4 votes vote down vote up
@Override
public boolean verifyToken(JWT token, RSAPublicKey publicKey) {
  JWSVerifier verifier = new RSASSAVerifier(publicKey);
  return token.verify(verifier);
}
 
Example #22
Source File: TokenServiceResourceTest.java    From knox with Apache License 2.0 4 votes vote down vote up
@Override
public boolean verifyToken(JWT token) {
  JWSVerifier verifier = new RSASSAVerifier(publicKey);
  return token.verify(verifier);
}
 
Example #23
Source File: WebSSOResourceTest.java    From knox with Apache License 2.0 4 votes vote down vote up
@Override
public boolean verifyToken(JWT token, RSAPublicKey publicKey) {
  JWSVerifier verifier = new RSASSAVerifier(publicKey);
  return token.verify(verifier);
}
 
Example #24
Source File: WebSSOResourceTest.java    From knox with Apache License 2.0 4 votes vote down vote up
@Override
public boolean verifyToken(JWT token) {
  JWSVerifier verifier = new RSASSAVerifier(publicKey);
  return token.verify(verifier);
}
 
Example #25
Source File: KnoxSSOAuthenticationFilter.java    From metron with Apache License 2.0 4 votes vote down vote up
protected RSASSAVerifier getRSASSAVerifier() throws CertificateException, IOException {
  return new RSASSAVerifier(SecurityUtils.parseRSAPublicKey(getKnoxKey()));
}
 
Example #26
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 #27
Source File: PoPAuthenticationManager.java    From OAuth-2.0-Cookbook with MIT License 4 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication)
    throws AuthenticationException {
    Authentication authenticationResult = authenticationManager
        .authenticate(authentication);

    if (authenticationResult.isAuthenticated()) {
        // validates nonce because JWT is already valid
        if (authentication instanceof PoPAuthenticationToken) {
            PoPAuthenticationToken popAuthentication = (PoPAuthenticationToken) authentication;

            // starts validating nonce here
            String nonce = popAuthentication.getNonce();
            if (nonce == null) {
                throw new UnapprovedClientAuthenticationException(
                    "This request does not have a valid signed nonce");
            }

            String token = (String) popAuthentication.getPrincipal();

            System.out.println("access token:" + token);

            try {
                JWT jwt = JWTParser.parse(token);
                String publicKey = jwt.getJWTClaimsSet().getClaim("public_key").toString();
                JWK jwk = JWK.parse(publicKey);

                JWSObject jwsNonce = JWSObject.parse(nonce);
                JWSVerifier verifier = new RSASSAVerifier((RSAKey) jwk);
                if (!jwsNonce.verify(verifier)) {
                    throw new InvalidTokenException("Client hasn't possession of given token");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
    }

    return authenticationResult;
}