Search in sources :

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

Example 8 with JwsSignatureVerifier

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

the class OAuth2JwtFiltersTest method doTestServiceWithJwtTokenAndScope.

private void doTestServiceWithJwtTokenAndScope(String oauthService, String rsAddress) throws Exception {
    URL busFile = OAuth2JwtFiltersTest.class.getResource("client.xml");
    // Get Authorization Code
    WebClient oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(), "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(oauthClient).getRequestContext().put(org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
    String code = OAuth2TestUtils.getAuthorizationCode(oauthClient, "create_book");
    assertNotNull(code);
    // Now get the access token
    oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(), "consumer-id", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(oauthClient).getRequestContext().put(org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
    ClientAccessToken accessToken = OAuth2TestUtils.getAccessTokenWithAuthorizationCode(oauthClient, code);
    assertNotNull(accessToken.getTokenKey());
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(accessToken.getTokenKey());
    JwsSignatureVerifier verifier = JwsUtils.loadSignatureVerifier("org/apache/cxf/systest/jaxrs/security/alice.rs.properties", null);
    assertTrue(jwtConsumer.verifySignatureWith(verifier));
    JwtClaims claims = jwtConsumer.getJwtClaims();
    assertEquals("consumer-id", claims.getStringProperty(OAuthConstants.CLIENT_ID));
    assertEquals("alice", claims.getStringProperty("username"));
    // Now invoke on the service with the access token
    WebClient client = WebClient.create(rsAddress, OAuth2TestUtils.setupProviders(), busFile.toString());
    client.header("Authorization", "Bearer " + accessToken.getTokenKey());
    Response response = client.type("application/xml").post(new Book("book", 123L));
    assertEquals(200, response.getStatus());
    Book returnedBook = response.readEntity(Book.class);
    assertEquals(returnedBook.getName(), "book");
    assertEquals(returnedBook.getId(), 123L);
}
Also used : JwsSignatureVerifier(org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier) Response(javax.ws.rs.core.Response) JwtClaims(org.apache.cxf.rs.security.jose.jwt.JwtClaims) Book(org.apache.cxf.systest.jaxrs.security.Book) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) WebClient(org.apache.cxf.jaxrs.client.WebClient) URL(java.net.URL)

Example 9 with JwsSignatureVerifier

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

the class JwsMultipartSignatureInFilter method filter.

@Override
public void filter(List<Attachment> atts) {
    if (atts.size() < 2) {
        throw ExceptionUtils.toBadRequestException(null, null);
    }
    Attachment sigPart = atts.remove(atts.size() - 1);
    String jwsSequence = null;
    try {
        jwsSequence = IOUtils.readStringFromStream(sigPart.getDataHandler().getInputStream());
    } catch (IOException ex) {
        throw ExceptionUtils.toBadRequestException(null, null);
    }
    String base64UrlEncodedHeaders = null;
    String base64UrlEncodedSignature = null;
    if (!useJwsJsonSignatureFormat) {
        String[] parts = JoseUtils.getCompactParts(jwsSequence);
        if (parts.length != 3 || parts[1].length() > 0) {
            throw ExceptionUtils.toBadRequestException(null, null);
        }
        base64UrlEncodedHeaders = parts[0];
        base64UrlEncodedSignature = parts[2];
    } else {
        Map<String, Object> parts = reader.fromJson(jwsSequence);
        if (parts.size() != 2 || !parts.containsKey("protected") || !parts.containsKey("signature")) {
            throw ExceptionUtils.toBadRequestException(null, null);
        }
        base64UrlEncodedHeaders = (String) parts.get("protected");
        base64UrlEncodedSignature = (String) parts.get("signature");
    }
    JwsHeaders headers = new JwsHeaders(new JsonMapObjectReaderWriter().fromJson(JoseUtils.decodeToString(base64UrlEncodedHeaders)));
    JoseUtils.traceHeaders(headers);
    if (Boolean.FALSE != headers.getPayloadEncodingStatus()) {
        throw ExceptionUtils.toBadRequestException(null, null);
    }
    JwsSignatureVerifier theVerifier = null;
    if (verifier == null) {
        Properties props = KeyManagementUtils.loadStoreProperties(message, true, JoseConstants.RSSEC_SIGNATURE_IN_PROPS, JoseConstants.RSSEC_SIGNATURE_PROPS);
        theVerifier = JwsUtils.loadSignatureVerifier(message, props, headers);
    } else {
        theVerifier = verifier;
    }
    JwsVerificationSignature sig = theVerifier.createJwsVerificationSignature(headers);
    if (sig == null) {
        throw ExceptionUtils.toBadRequestException(null, null);
    }
    byte[] signatureBytes = JoseUtils.decode(base64UrlEncodedSignature);
    byte[] headerBytesWithDot = StringUtils.toBytesASCII(base64UrlEncodedHeaders + ".");
    sig.update(headerBytesWithDot, 0, headerBytesWithDot.length);
    int attSize = atts.size();
    for (int i = 0; i < attSize; i++) {
        Attachment dataPart = atts.remove(i);
        InputStream dataPartStream = null;
        try {
            dataPartStream = dataPart.getDataHandler().getDataSource().getInputStream();
        } catch (IOException ex) {
            throw ExceptionUtils.toBadRequestException(ex, null);
        }
        boolean verifyOnLastRead = i == attSize - 1 ? true : false;
        JwsInputStream jwsStream = new JwsInputStream(dataPartStream, sig, signatureBytes, verifyOnLastRead);
        InputStream newStream = null;
        if (bufferPayload) {
            CachedOutputStream cos = new CachedOutputStream();
            try {
                IOUtils.copy(jwsStream, cos);
                newStream = cos.getInputStream();
            } catch (Exception ex) {
                throw ExceptionUtils.toBadRequestException(ex, null);
            }
        } else {
            newStream = jwsStream;
        }
        Attachment newDataPart = new Attachment(newStream, dataPart.getHeaders());
        atts.add(i, newDataPart);
    }
}
Also used : JwsInputStream(org.apache.cxf.rs.security.jose.jws.JwsInputStream) InputStream(java.io.InputStream) JsonMapObjectReaderWriter(org.apache.cxf.jaxrs.json.basic.JsonMapObjectReaderWriter) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) IOException(java.io.IOException) Properties(java.util.Properties) IOException(java.io.IOException) CachedOutputStream(org.apache.cxf.io.CachedOutputStream) JwsSignatureVerifier(org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier) JwsHeaders(org.apache.cxf.rs.security.jose.jws.JwsHeaders) JwsVerificationSignature(org.apache.cxf.rs.security.jose.jws.JwsVerificationSignature) JwsInputStream(org.apache.cxf.rs.security.jose.jws.JwsInputStream)

Example 10 with JwsSignatureVerifier

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

the class JwsClientResponseFilter method filter.

@Override
public void filter(ClientRequestContext req, ClientResponseContext res) throws IOException {
    if (isMethodWithNoContent(req.getMethod()) || isCheckEmptyStream() && !res.hasEntity()) {
        return;
    }
    JwsCompactConsumer p = new JwsCompactConsumer(IOUtils.readStringFromStream(res.getEntityStream()));
    JwsSignatureVerifier theSigVerifier = getInitializedSigVerifier(p.getJwsHeaders());
    if (!p.verifySignatureWith(theSigVerifier)) {
        throw new JwsException(JwsException.Error.INVALID_SIGNATURE);
    }
    byte[] bytes = p.getDecodedJwsPayloadBytes();
    res.setEntityStream(new ByteArrayInputStream(bytes));
    res.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length));
    String ct = JoseUtils.checkContentType(p.getJwsHeaders().getContentType(), getDefaultMediaType());
    if (ct != null) {
        res.getHeaders().putSingle("Content-Type", ct);
    }
    if (super.isValidateHttpHeaders()) {
        super.validateHttpHeadersIfNeeded(res.getHeaders(), p.getJwsHeaders());
    }
}
Also used : JwsSignatureVerifier(org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier) JwsException(org.apache.cxf.rs.security.jose.jws.JwsException) ByteArrayInputStream(java.io.ByteArrayInputStream) JwsCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsCompactConsumer)

Aggregations

JwsSignatureVerifier (org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier)13 ByteArrayInputStream (java.io.ByteArrayInputStream)4 JweDecryptionProvider (org.apache.cxf.rs.security.jose.jwe.JweDecryptionProvider)4 JwsCompactConsumer (org.apache.cxf.rs.security.jose.jws.JwsCompactConsumer)4 Principal (java.security.Principal)2 List (java.util.List)2 Properties (java.util.Properties)2 MultivaluedMap (javax.ws.rs.core.MultivaluedMap)2 JwsException (org.apache.cxf.rs.security.jose.jws.JwsException)2 JwsJsonConsumer (org.apache.cxf.rs.security.jose.jws.JwsJsonConsumer)2 JwsJsonSignatureEntry (org.apache.cxf.rs.security.jose.jws.JwsJsonSignatureEntry)2 JwsJwtCompactConsumer (org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer)2 JwtClaims (org.apache.cxf.rs.security.jose.jwt.JwtClaims)2 JwtToken (org.apache.cxf.rs.security.jose.jwt.JwtToken)2 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 URL (java.net.URL)1 KeyStore (java.security.KeyStore)1 X509Certificate (java.security.cert.X509Certificate)1 Map (java.util.Map)1