Search in sources :

Example 11 with JWSVerifier

use of com.nimbusds.jose.JWSVerifier in project java-docs-samples by GoogleCloudPlatform.

the class VerifyIapRequestHeader method verifyJwt.

private boolean verifyJwt(String jwtToken, String expectedAudience) throws Exception {
    // parse signed token into header / claims
    SignedJWT signedJwt = SignedJWT.parse(jwtToken);
    JWSHeader jwsHeader = signedJwt.getHeader();
    // header must have algorithm("alg") and "kid"
    Preconditions.checkNotNull(jwsHeader.getAlgorithm());
    Preconditions.checkNotNull(jwsHeader.getKeyID());
    JWTClaimsSet claims = signedJwt.getJWTClaimsSet();
    // claims must have audience, issuer
    Preconditions.checkArgument(claims.getAudience().contains(expectedAudience));
    Preconditions.checkArgument(claims.getIssuer().equals(IAP_ISSUER_URL));
    // claim must have issued at time in the past
    Date currentTime = Date.from(Instant.now(clock));
    Preconditions.checkArgument(claims.getIssueTime().before(currentTime));
    // claim must have expiration time in the future
    Preconditions.checkArgument(claims.getExpirationTime().after(currentTime));
    // must have subject, email
    Preconditions.checkNotNull(claims.getSubject());
    Preconditions.checkNotNull(claims.getClaim("email"));
    // verify using public key : lookup with key id, algorithm name provided
    ECPublicKey publicKey = getKey(jwsHeader.getKeyID(), jwsHeader.getAlgorithm().getName());
    Preconditions.checkNotNull(publicKey);
    JWSVerifier jwsVerifier = new ECDSAVerifier(publicKey);
    return signedJwt.verify(jwsVerifier);
}
Also used : ECDSAVerifier(com.nimbusds.jose.crypto.ECDSAVerifier) ECPublicKey(java.security.interfaces.ECPublicKey) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) JWSVerifier(com.nimbusds.jose.JWSVerifier) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSHeader(com.nimbusds.jose.JWSHeader) Date(java.util.Date)

Example 12 with JWSVerifier

use of com.nimbusds.jose.JWSVerifier in project knox by apache.

the class JWTTokenTest method testTokenSignature.

@Test
public void testTokenSignature() throws Exception {
    String[] claims = new String[4];
    claims[0] = "KNOXSSO";
    claims[1] = "john.doe@example.com";
    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("john.doe@example.com", 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((RSAPublicKey) publicKey);
    assertTrue(token.verify(verifier));
}
Also used : RSASSAVerifier(com.nimbusds.jose.crypto.RSASSAVerifier) JWSVerifier(com.nimbusds.jose.JWSVerifier) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) JWSSigner(com.nimbusds.jose.JWSSigner) Test(org.junit.Test)

Example 13 with JWSVerifier

use of com.nimbusds.jose.JWSVerifier in project oxAuth by GluuFederation.

the class JwtCrossCheckTest method validate.

private static void validate(String jwtAsString, OxAuthCryptoProvider cryptoProvider, String kid, SignatureAlgorithm signatureAlgorithm) throws Exception {
    SignedJWT signedJWT = SignedJWT.parse(jwtAsString);
    Jwt jwt = Jwt.parse(jwtAsString);
    JWSVerifier nimbusVerifier = null;
    AbstractJwsSigner oxauthVerifier = null;
    switch(signatureAlgorithm.getFamily()) {
        case EC:
            final ECKey ecKey = ECKey.load(cryptoProvider.getKeyStore(), kid, cryptoProvider.getKeyStoreSecret().toCharArray());
            final ECPublicKey ecPublicKey = ecKey.toECPublicKey();
            nimbusVerifier = new ECDSAVerifier(ecKey);
            oxauthVerifier = new ECDSASigner(jwt.getHeader().getSignatureAlgorithm(), new ECDSAPublicKey(jwt.getHeader().getSignatureAlgorithm(), ecPublicKey.getW().getAffineX(), ecPublicKey.getW().getAffineY()));
            break;
        case RSA:
            RSAKey rsaKey = RSAKey.load(cryptoProvider.getKeyStore(), kid, cryptoProvider.getKeyStoreSecret().toCharArray());
            final java.security.interfaces.RSAPublicKey rsaPublicKey = rsaKey.toRSAPublicKey();
            nimbusVerifier = new RSASSAVerifier(rsaKey);
            oxauthVerifier = new RSASigner(signatureAlgorithm, new RSAPublicKey(rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent()));
            break;
    }
    assertNotNull(nimbusVerifier);
    assertNotNull(oxauthVerifier);
    // Nimbus
    assertTrue(signedJWT.verify(nimbusVerifier));
    // oxauth cryptoProvider
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), kid, null, null, jwt.getHeader().getSignatureAlgorithm());
    assertTrue(validJwt);
    // oxauth verifier
    assertTrue(oxauthVerifier.validate(jwt));
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) ECDSASigner(org.gluu.oxauth.model.jws.ECDSASigner) Jwt(org.gluu.oxauth.model.jwt.Jwt) RSASSAVerifier(com.nimbusds.jose.crypto.RSASSAVerifier) JWSVerifier(com.nimbusds.jose.JWSVerifier) AbstractJwsSigner(org.gluu.oxauth.model.jws.AbstractJwsSigner) ECKey(com.nimbusds.jose.jwk.ECKey) SignedJWT(com.nimbusds.jwt.SignedJWT) ECDSAVerifier(com.nimbusds.jose.crypto.ECDSAVerifier) ECPublicKey(java.security.interfaces.ECPublicKey) RSAPublicKey(org.gluu.oxauth.model.crypto.signature.RSAPublicKey) RSASigner(org.gluu.oxauth.model.jws.RSASigner) ECDSAPublicKey(org.gluu.oxauth.model.crypto.signature.ECDSAPublicKey)

Example 14 with JWSVerifier

use of com.nimbusds.jose.JWSVerifier in project scoold by Erudika.

the class ScooldUtils method isValidJWToken.

boolean isValidJWToken(String secret, String jwt) {
    try {
        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;
}
Also used : MACVerifier(com.nimbusds.jose.crypto.MACVerifier) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) JWSVerifier(com.nimbusds.jose.JWSVerifier) SignedJWT(com.nimbusds.jwt.SignedJWT) ParseException(java.text.ParseException) JOSEException(com.nimbusds.jose.JOSEException) Date(java.util.Date)

Example 15 with JWSVerifier

use of com.nimbusds.jose.JWSVerifier in project ddf by codice.

the class OidcTokenValidator method validateUserInfoIdToken.

/**
 * Validates id tokens received from the userinfo endpoint.
 *
 * <ul>
 *   <li>If the ID token is not signed, validation is ignored
 *   <li>If the ID token is signed
 *       <ul>
 *         <li>If the userinfo signing algorithms are listed in the metadata, we use that
 *             information along with the header attributes to validate the token
 *         <li>If the userinfo signing algorithms are NOT listed in the metadata, we just use the
 *             header attributes to validate the token
 *       </ul>
 *
 * @param idToken - id token to validate
 * @param resourceRetriever - resource retriever
 * @param metadata - OIDC metadata
 */
public static void validateUserInfoIdToken(JWT idToken, ResourceRetriever resourceRetriever, OIDCProviderMetadata metadata) throws OidcValidationException {
    if (metadata == null) {
        LOGGER.debug("Oidc metadata is null. Unable to validate userinfo id token.");
        return;
    }
    if (resourceRetriever == null) {
        resourceRetriever = new DefaultResourceRetriever();
    }
    try {
        if (!(idToken instanceof SignedJWT)) {
            LOGGER.info("ID token received from the userinfo endpoint was not signed.");
            return;
        }
        JWKSource jwkSource = new RemoteJWKSet(metadata.getJWKSetURI().toURL(), resourceRetriever);
        SignedJWT signedJWT = ((SignedJWT) idToken);
        JWSAlgorithm jwsAlgorithm = signedJWT.getHeader().getAlgorithm();
        List<JWSAlgorithm> userInfoSigAlgList = metadata.getUserInfoJWSAlgs();
        if (userInfoSigAlgList.isEmpty()) {
            LOGGER.warn("A JWS algorithm was not listed in the OpenID Connect provider metadata. " + "Using JWS algorithm specified in the header.");
        } else {
            if (!userInfoSigAlgList.contains(jwsAlgorithm)) {
                LOGGER.error("The signature algorithm of the id token do not match the expected ones.");
                throw new OidcValidationException("The signature algorithm of the id token do not match the expected ones.");
            }
        }
        JWSKeySelector jwsKeySelector = new JWSVerificationKeySelector(jwsAlgorithm, jwkSource);
        JWSVerifierFactory jwsVerifierFactory = new DefaultJWSVerifierFactory();
        List<? extends Key> keyCandidates = jwsKeySelector.selectJWSKeys(signedJWT.getHeader(), null);
        if (keyCandidates == null || keyCandidates.isEmpty()) {
            throw new OidcValidationException("Error Validating userinfo ID token. No matching key(s) found");
        }
        ListIterator<? extends Key> it = keyCandidates.listIterator();
        while (it.hasNext()) {
            JWSVerifier verifier = jwsVerifierFactory.createJWSVerifier(signedJWT.getHeader(), it.next());
            if (verifier == null) {
                continue;
            }
            final boolean validSignature = signedJWT.verify(verifier);
            if (validSignature) {
                return;
            }
            if (!it.hasNext()) {
                throw new OidcValidationException("Error Validating userinfo ID token. Invalid signature");
            }
        }
        throw new OidcValidationException("Error Validating userinfo ID token. No matching verifier(s) found");
    } catch (Exception e) {
        LOGGER.error(ID_VALIDATION_ERR_MSG, e);
        throw new OidcValidationException(ID_VALIDATION_ERR_MSG, e);
    }
}
Also used : DefaultJWSVerifierFactory(com.nimbusds.jose.crypto.factories.DefaultJWSVerifierFactory) JWSVerifier(com.nimbusds.jose.JWSVerifier) JWSVerifierFactory(com.nimbusds.jose.proc.JWSVerifierFactory) DefaultJWSVerifierFactory(com.nimbusds.jose.crypto.factories.DefaultJWSVerifierFactory) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) JWKSource(com.nimbusds.jose.jwk.source.JWKSource) RemoteJWKSet(com.nimbusds.jose.jwk.source.RemoteJWKSet) JWSVerificationKeySelector(com.nimbusds.jose.proc.JWSVerificationKeySelector) JWSKeySelector(com.nimbusds.jose.proc.JWSKeySelector) DefaultResourceRetriever(com.nimbusds.jose.util.DefaultResourceRetriever)

Aggregations

JWSVerifier (com.nimbusds.jose.JWSVerifier)15 RSASSAVerifier (com.nimbusds.jose.crypto.RSASSAVerifier)10 SignedJWT (com.nimbusds.jwt.SignedJWT)9 JOSEException (com.nimbusds.jose.JOSEException)5 ECDSAVerifier (com.nimbusds.jose.crypto.ECDSAVerifier)3 RSAKey (com.nimbusds.jose.jwk.RSAKey)3 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)3 ECPublicKey (java.security.interfaces.ECPublicKey)3 ParseException (java.text.ParseException)3 Test (org.junit.Test)3 JWSSigner (com.nimbusds.jose.JWSSigner)2 MACVerifier (com.nimbusds.jose.crypto.MACVerifier)2 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)2 RSAPublicKey (java.security.interfaces.RSAPublicKey)2 Date (java.util.Date)2 ECCKeyPair (com.fitpay.android.api.models.security.ECCKeyPair)1 JWEHeader (com.nimbusds.jose.JWEHeader)1 JWEObject (com.nimbusds.jose.JWEObject)1 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)1 JWSHeader (com.nimbusds.jose.JWSHeader)1