Search in sources :

Example 36 with JWSVerifier

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

the class JWTRedirectAuthenticationHandler method validateSignature.

/**
 * 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;
}
Also used : RSASSAVerifier(com.nimbusds.jose.crypto.RSASSAVerifier) JWSVerifier(com.nimbusds.jose.JWSVerifier) JOSEException(com.nimbusds.jose.JOSEException)

Example 37 with JWSVerifier

use of com.nimbusds.jose.JWSVerifier in project jans by JanssenProject.

the class JwtCrossCheckTest method validate.

private static void validate(String jwtAsString, AuthCryptoProvider 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(io.jans.as.model.jws.ECDSASigner) Jwt(io.jans.as.model.jwt.Jwt) RSASSAVerifier(com.nimbusds.jose.crypto.RSASSAVerifier) JWSVerifier(com.nimbusds.jose.JWSVerifier) AbstractJwsSigner(io.jans.as.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(io.jans.as.model.crypto.signature.RSAPublicKey) RSASigner(io.jans.as.model.jws.RSASigner) ECDSAPublicKey(io.jans.as.model.crypto.signature.ECDSAPublicKey)

Example 38 with JWSVerifier

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

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 39 with JWSVerifier

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

the class ZTSImplTest method testPostSignedPolicyRequest.

@Test
public void testPostSignedPolicyRequest() throws ParseException, JOSEException {
    ChangeLogStore structStore = new ZMSFileChangeLogStore("/tmp/zts_server_unit_tests/zts_root", privateKey, "0");
    DataStore store = new DataStore(structStore, null, ztsMetric);
    ZTSImpl ztsImpl = new ZTSImpl(mockCloudStore, store);
    ZTSImpl.serverHostName = "localhost";
    SignedDomain signedDomain = createSignedDomain("coretech", "weather", "storage", true);
    store.processSignedDomain(signedDomain, false);
    Principal principal = SimplePrincipal.create("user_domain", "user", "v=U1;d=user_domain;n=user;s=signature", 0, null);
    ResourceContext context = createResourceContext(principal);
    SignedPolicyRequest signedPolicyRequest = new SignedPolicyRequest();
    signedPolicyRequest.setPolicyVersions(Collections.emptyMap());
    Response response = ztsImpl.postSignedPolicyRequest(context, "coretech", signedPolicyRequest, null);
    assertEquals(response.getStatus(), 200);
    JWSPolicyData jwsPolicyData = (JWSPolicyData) response.getEntity();
    JWSObject jwsObject = new JWSObject(Base64URL.from(jwsPolicyData.getProtectedHeader()), Base64URL.from(jwsPolicyData.getPayload()), Base64URL.from(jwsPolicyData.getSignature()));
    JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) Crypto.extractPublicKey(zts.privateKey.getKey()));
    assertTrue(jwsObject.verify(verifier));
    // verify that with p1363 signature and rsa - it's the same key so validation is successful
    signedPolicyRequest.setSignatureP1363Format(true);
    response = ztsImpl.postSignedPolicyRequest(context, "coretech", signedPolicyRequest, null);
    assertEquals(response.getStatus(), 200);
    jwsPolicyData = (JWSPolicyData) response.getEntity();
    jwsObject = new JWSObject(Base64URL.from(jwsPolicyData.getProtectedHeader()), Base64URL.from(jwsPolicyData.getPayload()), Base64URL.from(jwsPolicyData.getSignature()));
    assertTrue(jwsObject.verify(verifier));
    try {
        ztsImpl.postSignedPolicyRequest(context, "unknowndomain", signedPolicyRequest, null);
        fail();
    } catch (ResourceException ex) {
        assertEquals(ex.getCode(), 404);
    }
}
Also used : RSASSAVerifier(com.nimbusds.jose.crypto.RSASSAVerifier) JWSVerifier(com.nimbusds.jose.JWSVerifier) Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) ZMSFileChangeLogStore(com.yahoo.athenz.common.server.store.impl.ZMSFileChangeLogStore) ChangeLogStore(com.yahoo.athenz.common.server.store.ChangeLogStore) MockZMSFileChangeLogStore(com.yahoo.athenz.zts.store.MockZMSFileChangeLogStore) ZMSFileChangeLogStore(com.yahoo.athenz.common.server.store.impl.ZMSFileChangeLogStore) MockZMSFileChangeLogStore(com.yahoo.athenz.zts.store.MockZMSFileChangeLogStore) DataStore(com.yahoo.athenz.zts.store.DataStore) JWSObject(com.nimbusds.jose.JWSObject) Principal(com.yahoo.athenz.auth.Principal) Test(org.testng.annotations.Test)

Example 40 with JWSVerifier

use of com.nimbusds.jose.JWSVerifier in project Insights by CognizantOneDevOps.

the class TokenProviderUtility method verifyExternalTokenAndFetchClaims.

/**
 * Used to verify received token without cache
 *
 * @param token
 * @return
 * @throws AuthorizationServiceException
 * @throws AuthenticationCredentialsNotFoundException
 * @throws AccountExpiredException
 * @throws InsightsCustomException
 */
public JWTClaimsSet verifyExternalTokenAndFetchClaims(String token) throws InsightsCustomException {
    boolean isVerify = Boolean.FALSE;
    boolean validateTokenDate = Boolean.FALSE;
    JWTClaimsSet claims = null;
    log.debug(" In verifyExternalTokenAndFetchClaims method ==== ");
    try {
        String authToken = ValidationUtils.cleanXSS(token);
        if (authToken == null || authToken.isEmpty()) {
            log.error("External authToken is not valid or empty");
            throw new InsightsCustomException("Invalid External authToken or empty authToken");
        }
        // parse the JWS and verify its HMAC
        SignedJWT signedJWT = SignedJWT.parse(authToken);
        JWSVerifier verifier = new MACVerifier(signingKey);
        isVerify = signedJWT.verify(verifier);
        claims = signedJWT.getJWTClaimsSet();
        // signedJWT.getJWTClaimsSet().getClaims().forEach((k,v) -> log.debug(" k ======== {} v ======== {} ",k,v));
        validateTokenDate = new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime());
        if (!isVerify) {
            log.error("External Token signuture not match ");
            throw new AuthorizationServiceException("External Token signuture not match");
        } else if (!validateTokenDate) {
            throw new AccountExpiredException("External token validity Expire");
        } else {
            log.debug("External Token verified sucessfully ==== ");
        }
    } catch (Exception e) {
        log.error(e);
        log.error(" Exception while validating External token {} ", e.getMessage());
        throw new InsightsCustomException("Exception while varifing External token ==== " + e.getMessage());
    }
    return claims;
}
Also used : InsightsCustomException(com.cognizant.devops.platformcommons.exception.InsightsCustomException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) MACVerifier(com.nimbusds.jose.crypto.MACVerifier) AuthorizationServiceException(org.springframework.security.access.AuthorizationServiceException) AccountExpiredException(org.springframework.security.authentication.AccountExpiredException) JWSVerifier(com.nimbusds.jose.JWSVerifier) SignedJWT(com.nimbusds.jwt.SignedJWT) Date(java.util.Date) JOSEException(com.nimbusds.jose.JOSEException) AuthorizationServiceException(org.springframework.security.access.AuthorizationServiceException) CacheWritingException(org.ehcache.spi.loaderwriter.CacheWritingException) AuthenticationCredentialsNotFoundException(org.springframework.security.authentication.AuthenticationCredentialsNotFoundException) AccountExpiredException(org.springframework.security.authentication.AccountExpiredException) InsightsCustomException(com.cognizant.devops.platformcommons.exception.InsightsCustomException)

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