Search in sources :

Example 26 with JWSVerifier

use of com.nimbusds.jose.JWSVerifier in project Application-Gateway by gianlucafrei.

the class HmacJwtSignerTest method testHmacJwtSigner.

@Test
public void testHmacJwtSigner() throws Exception {
    // Arrange
    // hex string with mixed case
    String key = "DEADBEEFdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
    String keyId = "KeyID";
    String subject = "John Doe";
    var signer = new HmacJwtSigner(key, keyId);
    var claims = new JWTClaimsSet.Builder().subject(subject).build();
    JWSVerifier verifier = new MACVerifier(Hex.decodeHex(key));
    // Act
    var jwt = signer.createSignedJwt(claims);
    // Assert
    SignedJWT parsedJwt = SignedJWT.parse(jwt);
    assertEquals(keyId, parsedJwt.getHeader().getKeyID());
    assertEquals(subject, parsedJwt.getJWTClaimsSet().getSubject());
    assertEquals(JWSAlgorithm.HS256, parsedJwt.getHeader().getAlgorithm());
    assertTrue(parsedJwt.verify(verifier));
}
Also used : MACVerifier(com.nimbusds.jose.crypto.MACVerifier) JWSVerifier(com.nimbusds.jose.JWSVerifier) SignedJWT(com.nimbusds.jwt.SignedJWT) Test(org.junit.jupiter.api.Test)

Example 27 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)

Example 28 with JWSVerifier

use of com.nimbusds.jose.JWSVerifier in project athenz by yahoo.

the class ZMSImplTest method getDomainData.

private DomainData getDomainData(JWSDomain jwsDomain) throws ParseException, JOSEException, JsonProcessingException {
    assertNotNull(jwsDomain);
    JWSObject jwsObject = new JWSObject(Base64URL.from(jwsDomain.getProtectedHeader()), Base64URL.from(jwsDomain.getPayload()), Base64URL.from(jwsDomain.getSignature()));
    JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) Crypto.extractPublicKey(zmsTestInitializer.getZms().privateKey.getKey()));
    assertTrue(jwsObject.verify(verifier));
    return zmsTestInitializer.getZms().jsonMapper.readValue(jwsObject.getPayload().toString(), DomainData.class);
}
Also used : RSASSAVerifier(com.nimbusds.jose.crypto.RSASSAVerifier) JWSVerifier(com.nimbusds.jose.JWSVerifier) JWSObject(com.nimbusds.jose.JWSObject)

Example 29 with JWSVerifier

use of com.nimbusds.jose.JWSVerifier in project carbon-apimgt by wso2.

the class JWTWithRSASignatureImpl method verifyRSASignature.

/**
 * {@inheritDoc}
 */
@Override
public boolean verifyRSASignature(String token, RSAPublicKey rsaPublicKey) throws APIManagementException {
    if (token == null) {
        throw new IllegalArgumentException("The SignedJWT must not be null");
    }
    if (rsaPublicKey == null) {
        throw new IllegalArgumentException("The public key must not be null");
    }
    boolean isSignatureVerified;
    try {
        SignedJWT signedJWT = SignedJWT.parse(token);
        JWSVerifier verifier = new RSASSAVerifier(rsaPublicKey);
        isSignatureVerified = signedJWT.verify(verifier);
    } catch (ParseException e) {
        throw new APIManagementException("Error parsing signed JWT string ", e);
    } catch (JOSEException e) {
        throw new APIManagementException("Failed to verify signature ", e);
    }
    return isSignatureVerified;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) RSASSAVerifier(com.nimbusds.jose.crypto.RSASSAVerifier) JWSVerifier(com.nimbusds.jose.JWSVerifier) SignedJWT(com.nimbusds.jwt.SignedJWT) ParseException(java.text.ParseException) JOSEException(com.nimbusds.jose.JOSEException)

Example 30 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)

Aggregations

JWSVerifier (com.nimbusds.jose.JWSVerifier)53 RSASSAVerifier (com.nimbusds.jose.crypto.RSASSAVerifier)34 SignedJWT (com.nimbusds.jwt.SignedJWT)27 JOSEException (com.nimbusds.jose.JOSEException)20 RSAPublicKey (java.security.interfaces.RSAPublicKey)14 ParseException (java.text.ParseException)14 MACVerifier (com.nimbusds.jose.crypto.MACVerifier)10 JWSObject (com.nimbusds.jose.JWSObject)9 RSAKey (com.nimbusds.jose.jwk.RSAKey)8 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)8 Date (java.util.Date)8 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)6 ECDSAVerifier (com.nimbusds.jose.crypto.ECDSAVerifier)6 JWSVerificationKeySelector (com.nimbusds.jose.proc.JWSVerificationKeySelector)6 IOException (java.io.IOException)6 PublicKey (java.security.PublicKey)5 ECPublicKey (java.security.interfaces.ECPublicKey)5 Test (org.junit.Test)5 DefaultJWSVerifierFactory (com.nimbusds.jose.crypto.factories.DefaultJWSVerifierFactory)4 JWKSet (com.nimbusds.jose.jwk.JWKSet)4