Search in sources :

Example 1 with JwsSignatureVerifier

use of org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier in project cxf by apache.

the class OAuthServerJoseJwtConsumer method getInitializedSignatureVerifier.

protected JwsSignatureVerifier getInitializedSignatureVerifier(Client c) {
    JwsSignatureVerifier theSignatureVerifier = null;
    if (verifyWithClientCertificates && c != null && !c.getApplicationCertificates().isEmpty()) {
        X509Certificate cert = (X509Certificate) CryptoUtils.decodeCertificate(c.getApplicationCertificates().get(0));
        theSignatureVerifier = JwsUtils.getPublicKeySignatureVerifier(cert.getPublicKey(), SignatureAlgorithm.RS256);
    }
    if (theSignatureVerifier == null && c != null && c.getClientSecret() != null) {
        theSignatureVerifier = super.getInitializedSignatureVerifier(c.getClientSecret());
    }
    return theSignatureVerifier;
}
Also used : JwsSignatureVerifier(org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier) X509Certificate(java.security.cert.X509Certificate)

Example 2 with JwsSignatureVerifier

use of org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier in project cxf by apache.

the class JoseConsumer method getData.

public String getData(String data) {
    super.checkProcessRequirements();
    if (isJweRequired()) {
        JweCompactConsumer jweConsumer = new JweCompactConsumer(data);
        JweDecryptionProvider theDecryptor = getInitializedDecryptionProvider(jweConsumer.getJweHeaders());
        if (theDecryptor == null) {
            throw new JwtException("Unable to decrypt JWT");
        }
        if (!isJwsRequired()) {
            return jweConsumer.getDecryptedContentText(theDecryptor);
        }
        JweDecryptionOutput decOutput = theDecryptor.decrypt(data);
        data = decOutput.getContentText();
    }
    JwsCompactConsumer jwsConsumer = new JwsCompactConsumer(data);
    if (isJwsRequired()) {
        JwsSignatureVerifier theSigVerifier = getInitializedSignatureVerifier(jwsConsumer.getJwsHeaders());
        if (theSigVerifier == null) {
            throw new JwtException("Unable to validate JWT");
        }
        if (!jwsConsumer.verifySignatureWith(theSigVerifier)) {
            throw new JwtException("Invalid Signature");
        }
    }
    return jwsConsumer.getDecodedJwsPayload();
}
Also used : JwsSignatureVerifier(org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier) JweDecryptionOutput(org.apache.cxf.rs.security.jose.jwe.JweDecryptionOutput) JwsCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsCompactConsumer) JweCompactConsumer(org.apache.cxf.rs.security.jose.jwe.JweCompactConsumer) JweDecryptionProvider(org.apache.cxf.rs.security.jose.jwe.JweDecryptionProvider) JwtException(org.apache.cxf.rs.security.jose.jwt.JwtException)

Example 3 with JwsSignatureVerifier

use of org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier in project cxf by apache.

the class JwtRequestCodeFilter method process.

@Override
public MultivaluedMap<String, String> process(MultivaluedMap<String, String> params, UserSubject endUser, Client client) {
    String requestToken = params.getFirst(REQUEST_PARAM);
    String requestUri = params.getFirst(REQUEST_URI_PARAM);
    if (requestToken == null) {
        if (isRequestUriValid(client, requestUri)) {
            requestToken = WebClient.create(requestUri).accept(REQUEST_URI_CONTENT_TYPE).get(String.class);
        }
    } else if (requestUri != null) {
        LOG.warning("It is not valid to specify both a request and request_uri value");
        throw new SecurityException();
    }
    if (requestToken != null) {
        JweDecryptionProvider theDecryptor = super.getInitializedDecryptionProvider(client.getClientSecret());
        JwsSignatureVerifier theSigVerifier = getInitializedSigVerifier(client);
        JwtToken jwt = getJwtToken(requestToken, theDecryptor, theSigVerifier);
        JwtClaims claims = jwt.getClaims();
        // Check issuer
        String iss = issuer != null ? issuer : client.getClientId();
        if (!iss.equals(claims.getIssuer())) {
            throw new SecurityException();
        }
        // Check client_id - if present it must match the client_id specified in the request
        if (claims.getClaim(OAuthConstants.CLIENT_ID) != null && !claims.getStringProperty(OAuthConstants.CLIENT_ID).equals(client.getClientId())) {
            throw new SecurityException();
        }
        // Check response_type - if present it must match the response_type specified in the request
        String tokenResponseType = (String) claims.getClaim(OAuthConstants.RESPONSE_TYPE);
        if (tokenResponseType != null && !tokenResponseType.equals(params.getFirst(OAuthConstants.RESPONSE_TYPE))) {
            throw new SecurityException();
        }
        MultivaluedMap<String, String> newParams = new MetadataMap<>(params);
        Map<String, Object> claimsMap = claims.asMap();
        for (Map.Entry<String, Object> entry : claimsMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof Map) {
                Map<String, Object> map = CastUtils.cast((Map<?, ?>) value);
                value = jsonHandler.toJson(map);
            } else if (value instanceof List) {
                List<Object> list = CastUtils.cast((List<?>) value);
                value = jsonHandler.toJson(list);
            }
            newParams.putSingle(key, value.toString());
        }
        return newParams;
    }
    return params;
}
Also used : JwtClaims(org.apache.cxf.rs.security.jose.jwt.JwtClaims) JwsSignatureVerifier(org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier) JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) JweDecryptionProvider(org.apache.cxf.rs.security.jose.jwe.JweDecryptionProvider) List(java.util.List) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Map(java.util.Map)

Example 4 with JwsSignatureVerifier

use of org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier in project cxf by apache.

the class JoseSessionTokenProvider method decryptStateString.

private String decryptStateString(String sessionToken) {
    JweDecryptionProvider jwe = getInitializedDecryptionProvider();
    String stateString = jwe.decrypt(sessionToken).getContentText();
    JwsSignatureVerifier jws = getInitializedSigVerifier();
    if (jws != null) {
        stateString = JwsUtils.verify(jws, stateString).getDecodedJwsPayload();
    }
    return stateString;
}
Also used : JwsSignatureVerifier(org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier) JweDecryptionProvider(org.apache.cxf.rs.security.jose.jwe.JweDecryptionProvider)

Example 5 with JwsSignatureVerifier

use of org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier in project cxf by apache.

the class JWTTokenValidator method validateToken.

/**
 * Validate a Token using the given TokenValidatorParameters.
 */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOG.fine("Validating JWT Token");
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    String token = ((Element) validateTarget.getToken()).getTextContent();
    if (token == null || "".equals(token)) {
        return response;
    }
    if (token.split("\\.").length != 3) {
        LOG.log(Level.WARNING, "JWT Token appears not to be signed. Validation has failed");
        return response;
    }
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    // Verify the signature
    Properties verificationProperties = new Properties();
    Crypto signatureCrypto = stsProperties.getSignatureCrypto();
    String alias = stsProperties.getSignatureUsername();
    if (alias != null) {
        verificationProperties.put(JoseConstants.RSSEC_KEY_STORE_ALIAS, alias);
    }
    if (!(signatureCrypto instanceof Merlin)) {
        throw new STSException("Can't get the keystore", STSException.REQUEST_FAILED);
    }
    KeyStore keystore = ((Merlin) signatureCrypto).getKeyStore();
    verificationProperties.put(JoseConstants.RSSEC_KEY_STORE, keystore);
    JwsSignatureVerifier signatureVerifier = JwsUtils.loadSignatureVerifier(verificationProperties, jwt.getJwsHeaders());
    if (!jwtConsumer.verifySignatureWith(signatureVerifier)) {
        return response;
    }
    try {
        validateToken(jwt);
    } catch (RuntimeException ex) {
        LOG.log(Level.WARNING, "JWT token validation failed", ex);
        return response;
    }
    // Get the realm of the JWT Token
    if (realmCodec != null) {
        String tokenRealm = realmCodec.getRealmFromToken(jwt);
        response.setTokenRealm(tokenRealm);
    }
    if (isVerifiedWithAPublicKey(jwt)) {
        Principal principal = new SimplePrincipal(jwt.getClaims().getSubject());
        response.setPrincipal(principal);
        // Parse roles from the validated token
        if (roleParser != null) {
            Set<Principal> roles = roleParser.parseRolesFromToken(principal, null, jwt);
            response.setRoles(roles);
        }
    }
    validateTarget.setState(STATE.VALID);
    LOG.fine("JWT Token successfully validated");
    return response;
}
Also used : Element(org.w3c.dom.Element) STSException(org.apache.cxf.ws.security.sts.provider.STSException) Properties(java.util.Properties) KeyStore(java.security.KeyStore) JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) JwsSignatureVerifier(org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) Merlin(org.apache.wss4j.common.crypto.Merlin) SimplePrincipal(org.apache.cxf.common.security.SimplePrincipal) Principal(java.security.Principal) SimplePrincipal(org.apache.cxf.common.security.SimplePrincipal)

Aggregations

JwsSignatureVerifier (org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier)17 JwsCompactConsumer (org.apache.cxf.rs.security.jose.jws.JwsCompactConsumer)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 JweDecryptionProvider (org.apache.cxf.rs.security.jose.jwe.JweDecryptionProvider)4 JwsJwtCompactConsumer (org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer)4 List (java.util.List)3 JsonWebKey (org.apache.cxf.rs.security.jose.jwk.JsonWebKey)3 JwsJsonConsumer (org.apache.cxf.rs.security.jose.jws.JwsJsonConsumer)3 Principal (java.security.Principal)2 Date (java.util.Date)2 Map (java.util.Map)2 Properties (java.util.Properties)2 MultivaluedMap (javax.ws.rs.core.MultivaluedMap)2 SignatureAlgorithm (org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm)2 JwsException (org.apache.cxf.rs.security.jose.jws.JwsException)2 JwsJsonSignatureEntry (org.apache.cxf.rs.security.jose.jws.JwsJsonSignatureEntry)2 JwtClaims (org.apache.cxf.rs.security.jose.jwt.JwtClaims)2 JwtToken (org.apache.cxf.rs.security.jose.jwt.JwtToken)2 Generators (com.fasterxml.uuid.Generators)1 RandomBasedGenerator (com.fasterxml.uuid.impl.RandomBasedGenerator)1