Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

 

 

Table of Contents

Introduction

...

JOSE is a key piece of advanced OAuth2 and OpenId Connect applications but can also be successfully used for securing the regular HTTP web service communications.

CXF 3.0.x, 3.1.x and 3.2.0 provide a complete implementation of JOSE and offer a comprehensive utility and filter support for protecting JAX-RS services and clients with the help of JOSE.

CXF OAuth2 and OIDC modules are also depending on it.

New: Signature and Verification support for multiparts using JWS Detached Content mode.

New: Optional HTTP Header protection.

Maven Dependencies

...

Having the following dependency will let developers write JOSE JWS or JWE code:

Code Block
xml
xml
<dependency>
  <groupId>org.apache.cxf</groupId>
  <artifactId>cxf-rt-rs-security-jose</artifactId>
  <version>3.1.7</version>
</dependency>

...

Having the following dependency will let developers use JAX-RS JOSE filters which will sign and/or encrypt the data streams, and decrypt or/and validate the incoming JOSE sequences and make the original data available for the processing.

...

You may also need to include Bouncy CastleBouncyCastle for some of JWE encryption algorithms to be supported:

Code Block
xml
xml
<dependency>
     <groupId>org.bouncycastle</groupId>
     <artifactId>bcprov-ext-jdk15on</artifactId>
     <version>1.54<60</version>
</dependency>

BouncyCastle provider can be registered and unregistered as follows:

Code Block
languagejava
titleBouncyCastle Provider
import java.security.Security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

private static void registerBouncyCastle() throws Exception {
    Security.addProvider(new BouncyCastleProvider());    
}

private static void unregisterBouncyCastle() throws Exception {
    Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);    
}

...


Java and JCE Policy 

Java7 or higher is recommended in most cases.

JWE

: Java6 does not support JWE AES -GCM at all GCM key wrap and content encryption algorithms (while with BouncyCastle it is not possible to submit JWE Header properties as an extra input to the encryption process to get them integrity protected which is not JWE compliant), however with Java 6 one can use AesCbcHmac content encryption if BouncyCastle is installed.

Unlimited JCE Policy for Java 7/8/9 needs to be installed if a size of the encryption key is 256 bits (example, JWE A256GCM).

JWS

Java 6 should also be fine but note only CXF 3.0.x can be run with Java 6.

JOSE Overview and Implementation

...

Code Block
languagejs
titlePublic RSA Key
{
  "kty":"RSA",
  "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx
     4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMs
     tn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2
     QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbI
     SD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqb
     w0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
  "e":"AQAB",
  "alg":"RS256",
  "kid":"Public RSA Key"
}

A 'kid' property can be of special interest as it allows to identify a key but also help with the simple key rotation mechanism realized (ex, OIDC Asymmetric Key Rotation).

...

Code Block
languagejava
titleJWK examples
InputStream is = JsonWebKeyTest.class.getResourceAsStream(fileName);
JsonWebKeys keySet = JwkUtils.readJwkSet(is);
JsonWebKey key = keySet.getKey("Public RSA Key");
String thumbprint = JwkUtils.getThumbprint(key);
assertEquals("NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs", thumbprint);
KeyType keyType = key.getKeyType();
assertEquals(KeyType.RSA, thumbprintkeyType);

JsonWebKeys

...

also

...

supports

...

the

...

retrieval

...

of

...

keys

...

by

...

their

...

type

...

(RSA,

...

EC,

...

Octet)

...

and

...

operation

...

(ENCRYPT,

...

SIGN,

...

etc).

...


Once

...

you

...

have

...

JWK

...

loaded

...

it

...

is

...

typically

...

submitted

...

to

...

JWS

...

or

...

JWE

...

providers.

JWS Signature

JWS (JSON Web Signature) document describes how a document content can be signed. For example, Appendix A1 shows how the content can be signed with an HMAC key

...

The following table shows the algorithms and the corresponding providers (org.apache.cxf.rs.security.jose.jws package):

AlgorithmJWS Header 'alg'JwsSignatureProviderJwsSignatureVerifier
HMACHS256, HS384, HS512

HmacJwsSignatureProvider

HmacJwsSignatureVerifier

RSASSA-PKCS1-v1_5RS256, RS384, RS512PrivateKeyJwsSignatureProviderPublicKeyJwsSignatureVerifier
ECDSAES256, ES384, ES512EcDsaJwsSignatureProviderEcDsaJwsSignatureVerifier
RSASSA-PSSPS256, PS384, PS512PrivateKeyJwsSignatureProviderPublicKeyJwsSignatureVerifier
NonenoneNoneJwsSignatureProviderNoneJwsSignatureVerifier

Either of these providers (except for None) can be initialized with the keys loaded from JWK or Java JKS stores or from the in-memory representations.

...

 For example, here is how an Appendix A1 example can be done in CXF: 

Code Block
languagejava
titleCXF JWS Compact HMac
JwtClaims claims = new JwtClaims();
claims.setIssuer("joe");
claims.setExpiryTime(1300819380L);
claims.setClaim("http://example.com/is_root", Boolean.TRUE);

JwsCompactProducer jwsProducer = new JwsJwtCompactProducer(claims);

// Sign
// Load HmacJwsSignatureProvider directly, see the next example for the alternative approach
String jwsSequence = jwsProducer.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY, SignatureAlgorithm.HS256));

// Validate
JwsJwtCompactConsumer jwsConsumer = new JwsJwtCompactConsumer(jwsSequence);

// Load HmacJwsSignatureVerifier directly, see the next example for the alternative approach
jwsConsumer.verifySignatureWith(new HmacJwsSignatureVerifier(ENCODED_MAC_KEY, SignatureAlgorithm.HS256)));

// Get the data
JwtClaims protectedClaims = jws.getJwtClaims();

...

JwsJsonProducer and JwsJsonConsumer support producing and consuming JWS JSON sequences.

 

Code Block
languagejava
titleCXF JWS JSON
JwsJsonProducer producer = new JwsJsonProducer(UNSIGNED_PLAIN_JSON_DOCUMENT);
JwsHeaders headerEntries = new JwsHeaders(SignatureAlgorithm.HS256);
              
producer.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY_1, SignatureAlgorithm.HS256),
                  headerEntries);
producer.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY_2, SignatureAlgorithm.HS256),
                  headerEntries);
assertEquals(DUAL_SIGNED_JWS_JSON_DOCUMENT, producer.getJwsJsonSignedDocument());

JwsJsonConsumer consumer = new JwsJsonConsumer(DUAL_SIGNED_DOCUMENT); 

// Validate both signatures, see below how to validate and produce
JsonWebKeys jwks = readKeySet("jwkSet.txt");
        
List<JwsJsonSignatureEntry> sigEntries = consumer.getSignatureEntries();
assertEquals(2, sigEntries.size());

// 1st signature
String firstKid = (String)sigEntries.get(0).getKeyId();
JsonWebKey firstKey = jwks.getKey(firstKid);
assertTrue(sigEntries.get(0).verifySignatureWith(firstKey));
// 2nd signature
String secondKid = (String)sigEntries.get(1).getKeyId();
JsonWebKey secondKey = jwks.getKey(secondKid);
assertTrue(sigEntries.get(1).verifySignatureWith(secondKey));

// or if you wish to validate (ex with the firstKey loaded above) and forward it to the next consumer, do:
JwsSignatureProvider provider = JwsUtils.getSignatureProvider(firstKey);
String nextJwsJson = consumer.validateAndProduce(Collections.singletonList(provider));
// use WebClient to post nextJwsJson to the next consumer, with nextJwsJson being nearly identical to the original
// double-signed JWS JSON signature, minus the signature which was already validated, in this case nextJwsJson will 
// only have a single signature 

...

JWS with Detached Content

JWS with a Detached Content provides a way to integrity-protect some data without actually having these data included in the resulting JWS sequence.

For example, if the producer and consumer can both access the same shared piece of data, then the producer can sign these data, post the JWS sequence (without the data) to the consumer. The consumer will validate this JWS sequence and assert the data have not been modified by the time it has received and started validating the sequence. JWS Compact and JWS JSON Producer and Consumer provider constructors accept an optional 'detached' flag in cases were it is required.      

Note the detached content mode is used to support the signing and verification of CXF multipart attachment parts, see below for more information.

JWS with Unencoded Payload

...

In CXF you can apply this option to both JWS Compact (embedded payloads - from CXF 3.1.7) and JWS JSON sequences, here is a JWS JSON code fragment: 


Code Block
languagejava
titleJWS JSON Unencoded
JwsJsonProducer producer = new JwsJsonProducer(UNSIGNED_PLAIN_JSON_DOCUMENT, true);
JwsHeaders headers = new JwsHeaders(SignatureAlgorithm.HS256);
headers.setPayloadEncodingStatus(false);
producer.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY_1, SignatureAlgorithm.HS256),
                  headers);

Note that JWS Compact uses a '.' as a separator between its 3 parts. JWS with Unencoded Payload recommends that it is the application's responsibility to deal with the unencoded payloads which may have '.' characters. Similarly, JWS JSON unencoded payloads with double quotes will need to be taken care of by the application. 

Note the the signing and verification of CXF multipart attachment parts does depend on this unencoded payload feature, see below for more information.

JWE Encryption

JWE (JSON Web Encryption) document describes how a document content, and, when applicable, a content encryption key, can be encrypted. For example, Appendix A1 shows how the content can be encrypted with a secret key using AesGcm with the actual content encryption key being encrypted using RSA-OAEP.

...

The following table shows the key encryption algorithms and the corresponding providers (org.apache.cxf.rs.security.jose.jwe package):

AlgorithmJWE Header 'alg'KeyEncryptionProviderKeyDecryptionProvider
RSAES-PKCS1-v1_5

RSA1_5

RSAKeyEncryptionAlgorithm

RSAKeyDecryptionAlgorithm

RSAES OAEP

RSA-OAEP, RSA-OAEP-256

RSAKeyEncryptionAlgorithmRSAKeyDecryptionAlgorithm
AES Key Wrap

A128KW, A192KW, A256KW

AesKeyWrapEncryptionAlgorithmAesKeyWrapDecryptionAlgorithm
DirectdirDirectKeyEncryptionAlgorithmDirectKeyDecryptionAlgorithm
ECDH-ES Key Wrap

ECDH-ES+A128KW (+A192KW, +256KW)

EcdhAesWrapKeyEncryptionAlgorithmEcdhAesWrapKeyDecryptionAlgorithm
ECDH-ES Direct

ECDH-ES

EcdhDirectKeyJweEncryptionEcdhDirectKeyJweDecryption
AES-GCM Key Wrap

A128GCMKW, A192GCMKW, A256GCMKW

AesGcmWrapKeyEncryptionAlgorithmAesGcmWrapKeyDecryptionAlgorithm
PBES2

PBES2-HS256+A128KW

PBES2-HS384+A192KW

PBES2-HS512+A256KW

PbesHmacAesWrapKeyEncryptionAlgorithmPbesHmacAesWrapKeyDecryptionAlgorithm

...


RSA-OAEP algorithms are likely to be used most often at the moment due to existing JKS stores being available everywhere and a relatively easy way of making the public validation keys available.

BouncyCastle is required if you use AES Key or AES-GCM Key Wrap or PBES2 key encryption.

ContentEncryptionProvider supports encrypting a generated content-encryption key, ContentDecryptionProvider - decrypting it.

The following table shows the content encryption algorithms and the corresponding providers:

AlgorithmJWE Header 'enc'ContentEncryptionProviderContentDecryptionProvider
AES_CBC_HMAC_SHA2

A128CBC-HS256(-HS384, -HS512)

AesCbcHmacJweEncryption,

AesCbcHmacJweDecryption

AES-GCM

A128GCM, A92GCM, A256GCM

AesGcmContentEncryptionAlgorithmAesGcmContentDecryptionAlgorithm

All of the above providers can be initialized with the keys loaded from JWK or Java JKS stores or from the in-memory representations.

BouncyCastle is required if you use AES_CBC_HMAC content encryption.

Once you have decided which key and content encryption algorithms need to be supported you can initialize JwsEncryptionProvider and JwsDecryptionProvider which do the actual JWE encryption/decryption work by coordinating with the key and content encryption providers. CXF ships JweEncryption (JwsEncryptionProvider) and JweDecryption (JweDecryptionProvider) helpers, simply pass them the preferred key and content encryption providers and have the content encrypted or decrypted.

...

Code Block
languagejava
titleCXF Jwe AesWrapAesCbcHMac
final String specPlainText = "Live long and prosper.";
        
AesWrapKeyEncryptionAlgorithm keyEncryption = new AesWrapKeyEncryptionAlgorithm(KEY_ENCRYPTION_KEY_A3, KeyAlgorithm.A128KW);
JweEncryptionProvider encryption = new AesCbcHmacJweEncryption(ContentAlgorithm.A128CBC_HS256,
                                                               keyEncryption);
String jweContent = encryption.encrypt(specPlainText.getBytes("UTF-8"), null);
        
AesWrapKeyDecryptionAlgorithm keyDecryption = new AesWrapKeyDecryptionAlgorithm(cekEncryptionKey);
JweDecryptionProvider decryption = new AesCbcHmacJweDecryption(keyDecryption);
String decryptedText = decryption.decrypt(jweContent).getContentText();
assertEquals(specPlainText, decryptedText);

 


Here is another example using RSA-OAEP key encryption and AES-GCM content encryption:

...

Code Block
languagejava
titleCXF JweJson
final String text = "The true sign of intelligence is not knowledge but imagination.";
// Create the secret keys for encrypting the content encryption key:
SecretKey wrapperKey1 = CryptoUtils.createSecretKeySpec(WRAPPER_BYTES1, "AES");
SecretKey wrapperKey2 = CryptoUtils.createSecretKeySpec(WRAPPER_BYTES2, "AES");

// Create KeyEncryptionProviders initialized with these secret keys: 
JweHeadersKeyEncryptionProvider protectedHeaderskeyEncryption1 = new JweHeaders(ContentAlgorithm.A128GCMJweUtils.getSecretKeyEncryptionAlgorithm(wrapperKey1, KeyAlgorithm.A128KW);
JweHeadersKeyEncryptionProvider sharedUnprotectedHeaderskeyEncryption2 = new JweHeaders();
sharedUnprotectedHeaders.setJsonWebKeysUrl("https://server.example.com/keys.jwks");
sharedUnprotectedHeaders.setKeyEncryptionAlgorithm(JweUtils.getSecretKeyEncryptionAlgorithm(wrapperKey2, KeyAlgorithm.A128KW);

// If you work with the public keys do this 
ContentEncryptionProvider contentEncryptioninstead:
// PublicKey publicKey1 = JweUtils..getContentEncryptionProvider(ContentAlgorithm.A128GCM);
//        
KeyEncryptionProvider KeyEncryptionProvider keyEncryption1 = JweUtils.getSecretKeyEncryptionAlgorithmgetPublicKeyEncryptionProvider(wrapperKey1publicKey1, KeyAlgorithm.A128KWRSA_AEP);
JweEncryptionProvider jweEnc1// PublicKey publicKey2 = new JweEncryption(keyEncryption1, contentEncryption);

...;
// KeyEncryptionProvider keyEncryption2 = JweUtils.getSecretKeyEncryptionAlgorithmgetPublicKeyEncryptionProvider(wrapperKey2publicKey2, KeyAlgorithm.A128KWRSA_AEP);
JweEncryptionProvider jweEnc2 = new JweEncryption(keyEncryption2, contentEncryption);

List<JweEncryptionProvider> jweList


// Create ContentEncryptionProvider:
// Starting from CXF 3.1.11:
ContentEncryptionProvider contentEncryption = new LinkedList<JweEncryptionProvider>();
jweList.add(jweEnc1);
jweList.add(jweEnc2);
        
JweJsonProducer p = new JweJsonProducer(protectedHeaders,
                                        sharedUnprotectedHeaders,
                                        StringUtils.toBytesUTF8(text),
                                        StringUtils.toBytesUTF8(EXTRA_AAD_SOURCE),
                                        false);
String jweJsonOut = p.encryptWith(jweList);

// first consumer:
JweDecryptionProvider jweDecrypt = JweUtils.createJweDecryptionProvider(wrapperKey1, 
               AesGcmContentEncryptionAlgorithm(ContentAlgorithm.A128GCM, true);
// or 
// ContentEncryptionProvider contentEncryption = JweUtils.getContentEncryptionProvider(ContentAlgorithm.A128GCM, true);

// Before CXF 3.1.1 a CEK needs to be pre-generated when dealing with multiple recipients:
//ContentEncryptionProvider contentEncryption = new AesGcmContentEncryptionAlgorithm(CEK_BYTES, ContentAlgorithm.A128GCM);

// If a single recipient then this line is enough:
//ContentEncryptionProvider contentEncryption = JweUtils.getContentEncryptionProvider(ContentAlgorithm.A128GCM);

// Prepare JweEncryptionProviders, one per each recipient.
List<JweEncryptionProvider> jweProviders = new LinkedList<JweEncryptionProvider>();
jweProviders.add(new JweEncryption(keyEncryption1, contentEncryption));
jweProviders.add(new JweEncryption(keyEncryption2, contentEncryption));


// Let the recipients know that the key encryption algorithm is A128KW. 
// This step is optional if the recipients support A128KW only.
// Note because these headers are shared A128KW needs to be supported by all the recipients.
// Per-reciepient specific headers can be used instead to note the key encryption algorithm if required.
// One can also consider setting this property in the shared protected headers, same as it is done below
// with the content algorithm

JweHeaders sharedUnprotectedHeaders = new JweHeaders();
sharedUnprotectedHeaders.setKeyEncryptionAlgorithm(KeyAlgorithm.A128KW);
// Set some other custom shared unprotected header
sharedUnprotectedHeaders.setHeader("customHeader", "customValue");

// Let the recipients know that the content encryption algorithm is A128GCM. 
// This step is optional if the recipients support A128GCM only.
JweHeaders protectedHeaders = new JweHeaders(ContentAlgorithm.A128GCM);

// Set per-recipient specific headers        
List<JweHeaders> perRecipientHeades = new LinkedList<JweHeaders>();
perRecipientHeades.add(new JweHeaders("key1"));
perRecipientHeades.add(new JweHeaders("key2"));

JweJsonProducer p = new JweJsonProducer(protectedHeaders,
                                        sharedUnprotectedHeaders,
          KeyAlgorithm.A128KW, 
                             StringUtils.toBytesUTF8(text),
                                    ContentAlgorithm.A128GCM);
JweJsonConsumer c = new JweJsonConsumer(jweJsonOut);
// the consumer will iterate over JWE entries and will try to find the one which can be decrypted with this decryptor
// which is always precise if only a single receipient entry is available
// or do consumer.getRecipientsMap() returning a list of entries and their metadata to do a more precise selection.

String content = consumer.decryptWith(jweDecrypt).getContent();

If the sequence contains a single recipient entry only then the JWE JSON 'recipients' array will contain a single entry, or the whole sequence can be flattened instead with the actual 'recipients' array dropped. JweJsonProducer  does not produce the flattened sequence when only a single encryption is done by default because 3rd party JWE JSON consumers may only be able to process the sequences with the 'recipients' array, so pass a 'canBeFlat' flag to JwEJsonProducer if needed

Does it make sense to use JWE JSON if you do not plan to do multiple encryptions ? Most likely you will prefer JWE Compact if only a single recipient is targeted.

JSON Web Token

JWT (JSON Web Token) is a collection of claims in JSON format. It is simply a regular JSON document where each top elevel property is called a 'claim'.

JWT can be JWS signed and/or JWE encrypted like any other data structure.

JWT is mainly used in OAuth2 and OIDC applications to represent self-contained OAuth2 access tokens, OIDC IdToken, UserInfo, but can also be used in other contexts. For example, see the section below on linking JWT authentication tokens to JWS or JWE secured payloads.

CXF offers a JWT support in this package. Typically one would create a set of claims and submit them to JWS/JWE JWT processors, for example, see a JWS section above.

JWS and JWE Combined

If you have a requirement to sign the data and then encrypt the signed payload then it can be easily achieved by selecting a required JWS Producer and creating a JWS Compact sequence, and next submitting this sequence to a JWE producer, and processing it all in the reverse sequence

JOSE JAX-RS Filters

 

While working directly with JWS and JWE providers may be needed in the application code, JAX-RS users writing the code like this:

StringUtils.toBytesUTF8(EXTRA_AAD_SOURCE),
                                        false);
String jweJsonOut = p.encryptWith(jweProviders, perRecipientHeades);

JweJsonConsumer consumer = new JweJsonConsumer(jweJsonOut);
KeyAlgorithm keyAlgo = consumer.getSharedUnprotectedHeader().getKeyEncryptionAlgorithm();
ContentAlgorithm ctAlgo = consumer.getProtectedHeader().getContentEncryptionAlgorithm();

// first recipient:
JweDecryptionProvider jwe1 = JweUtils.createJweDecryptionProvider(wrapperKey1, keyAlgo, ctAlgo);

// the consumer will iterate over JWE entries and will try to find the one which can be decrypted with this decryptor
// or do consumer.getRecipientsMap() returning a list of entries and their metadata to do a more precise selection.

String content = consumer.decryptWith(jwe1, Collections.singletonMap("kid", "key1")).getContent();

// second recipient:
JweDecryptionProvider jwe2 = JweUtils.createJweDecryptionProvider(wrapperKey2, keyAlgo, ctAlgo);
content = consumer.decryptWith(jwe2, Collections.singletonMap("kid", "key2")).getContent();

If the sequence contains a single recipient entry only then the JWE JSON 'recipients' array will contain a single entry, or the whole sequence can be flattened instead with the actual 'recipients' array dropped. JweJsonProducer  does not produce the flattened sequence when only a single encryption is done by default because 3rd party JWE JSON consumers may only be able to process the sequences with the 'recipients' array, so pass a 'canBeFlat' flag to JwEJsonProducer if needed

Does it make sense to use JWE JSON if you do not plan to do multiple encryptions ? Most likely you will prefer JWE Compact if only a single recipient is targeted.

JSON Web Token

JWT (JSON Web Token) is a collection of claims in JSON format. It is simply a regular JSON document where each top elevel property is called a 'claim'.

JWT can be JWS signed and/or JWE encrypted like any other data structure.

JWT is mainly used in OAuth2 and OIDC applications to represent self-contained OAuth2 access tokens, OIDC IdToken, UserInfo, but can also be used in other contexts. For example, see the section below on linking JWT authentication tokens to JWS or JWE secured payloads.

CXF offers a JWT support in this package. Typically one would create a set of claims and submit them to JWS/JWE JWT processors, for example, see a JWS section above.

JWS and JWE Combined

If you have a requirement to sign the data and then encrypt the signed payload then it can be easily achieved by selecting a required JWS Producer and creating a JWS Compact sequence, and next submitting this sequence to a JWE producer, and processing it all in the reverse sequence.

JOSE JAX-RS Filters


While working directly with JWS and JWE providers may be needed in the application code, JAX-RS users writing the code like this:

Code Block
languagejava
titleTypical JAX-RS code
@Path("/
Code Block
languagejava
titleTypical JAX-RS code
@Path("/bookstore")
public class BookStore {
    
    public BookStore() {
    }
    
    @POST
    @Path("/books")
    @Produces("text/plain")
    @Consumes("text/plain")
    public String echoText(String text) {
        return text;
    }
    
    @POST
    @Path("/books")
    @Produces("application/json")
    @Consumes("application/json")
    public Book echoBook(Book book) {
        return book;
    }
}

...

Register both JWS and JWE out filters if the data need to be signed and encrypted (the filters are ordered such that the data are signed first and encrypted next) and JWS and JWE in filters if the signed data need to be decrypted first and then verified.

JWS

JWS Compact

JwsWriterInterceptor creates compact JWS sequences on the client or server out directions. For example, if you have the client code posting a Book or the server code returning a Book, with this Book representation expected to be signed, then add JwsWriterInterceptor and set the signature properties on the JAX-RS client or server.

...

No Format
Address: https://localhost:9001/jwsjwkhmac/bookstore/books
Http-Method: POST
Content-Type: application/jose
Payload: 
eyJhbGciOiJIUzI1NiIsImN0eSI6Impzb24ifQ.
eyJCb29rIjp7ImlkIjoxMjMsIm5hbWUiOiJib29rIn19.
hg1T41ESuX6JvRR--huTA3HnbrsdIZSwkxQdyWj9j6c

org.apache.cxf.rs.security.jose.common.JoseUtils traceHeaders
INFO: JWS Headers: 
{"alg":"HS256",
 "cty":"json"}

...


You can see 3 JWS parts (put on separate lines for the better readibility) separated by dots. The 1st part is Base64Url encoded protected headers, next one - Base64Url encoded Book JSON payload, finally - the signature.

...

Code Block
languagejava
titleClient JWS SetUp
    	public void testJwsJwkBookHMac() throws Exception {
        String address = "https://localhost:" + PORT + "/jwsjwkhmac";
        BookStore bs = createJwsBookStore(address);
        Book book = bs.echoBook(new Book("book", 123L));
        assertEquals("book", book.getName());
        assertEquals(123L, book.getId());
    }
    private BookStore createJwsBookStore(String address, 
                                         List<?> mbProviders) throws Exception {
        JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
        bean.setServiceClass(BookStore.class);
        bean.setAddress(address);
        List<Object> providers = new LinkedList<Object>();
        // JWS Compact Out
        JwsWriterInterceptor jwsWriter = new JwsWriterInterceptor();
        // enable streaming 
        jwsWriter.setUseJwsOutputStream(true);
        providers.add(jwsWriter);
        // JWS Compact In
// The payload is encoded by default, disable it if required
         providers// jwsWriter.setEncodePayload(false);
        providers.add(jwsWriter);
        // JWS Compact In
        providers.add(new JwsClientResponseFilter());
        // Book to/from JSON
        providers.add(new JacksonJsonProvider());
        bean.setProviders(providers);
        // point to the JWS security properties
        bean.getProperties(true).put("rs.security.signature.properties", 
            "org/apache/cxf/systest/jaxrs/security/secret.jwk.properties");
        // enable the tracing of JWS headers
        bean.getProperties(true).put("jose.debug", true);
        
        return bean.create(BookStore.class);
    }

The above code shows a client proxy code but WebClient can be created instead. The server is configured here. The client can be configured in Spring/Blueprint too.

JWS Compact With Unencoded Payload

Starting from CXF 3.1.7 it is also possible to produce JWS Compact sequences with the unencoded payload (See JWS With Clear Unencoded Payload above for restrictions).

...

Note that a 2nd part, "book", is not Base64Url encoded. Set an 'encodePayload' option on the request or response JWS Compact filter to 'false'.

JWS JSON

JwsJsonWriterInterceptor creates JWS JSON sequences on the client or server out directions. 

...

Note the Base64Url encoded payload goes first, followed by the 'signatures' array, with each element containing the protected headers and the actual signature specific to a given signature key.

JWS JSON with Unencoded Payload

Enabling the clear unencoded JWS payload option wilkl will produce:

No Format
{
 "payload" : "book",  
 "signatures": 
   [
      {
       "protected" : "eyJhbGciOiJIUzI1NiIsImN0eSI6InRleHQvcGxhaW4iLCJiNjQiOmZhbHNlLCJjcml0IjpbImI2NCJdfQ",
       "signature" : "fM7O2IVO3NsQeTGrFiMeLf_TKTsMSqnqmjnK40PwQ88"
      }
   ]
}

The client code and server configuration is nearly identical to a code/configuration needed to set up JWS Compact filters as shown above, simply replace JwsWriterInterceptor/JwsClientResponseFilter with JwsJsonWriterInterceptor/JwsJsonClientResponseFilter in the client code, and JwsContainerRequestFilter/JwsContainerResponseFilter with JwsJsonContainerRequestFilter/JwsJsonContainerResponseFilter

JWE

JweWriterInterceptor creates Compact JWE sequences on the client or server out directions. For example, if you have the client code posting a Book or the server code returning a Book, with this Book representation expected to be encrypted, then add JweWriterInterceptor and set the encryption properties on the JAX-RS client or server.

JweClientResponseFilter and JweContainerRequestFilter process the incoming client or server Compact JWE sequences.

Here is an example of a plain text "book" being encrypted with the A128KW key and A128GCM content encryption (see JWE section above), converted into Compact JWE and POSTed to the target service:

No Format
Address: https://localhost:9001/jwejwkaeswrap/bookstore/books
Http-Method: POST
Content-Type: application/jose
Payload: 
eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4R0NNIiwiY3R5IjoidGV4dC9wbGFpbiJ9.
SQul1USvHmADDLpBvY2Dnqk5GpoowOkJ.
cFuCSzRsl6GZuvHL.
akVT5g.
i8rpTk-v0b1IyE1sVT1IOA

org.apache.cxf.rs.security.jose.common.JoseUtils traceHeaders
INFO: JWE Headers: 
{"alg":"A128KW",
 "enc":"A128GCM",
 "cty":"text/plain"}

You can see 5 JWE parts (put on separate lines for the better readibility) separated by dots. The 1st part is Base64Url encoded protected headers, next one - Base64Url encoded content encryption key, next one - Base64Url encoded IV, next one - Base64Url encoded ciphertext, finally - the authentication tag.

Note that the protected headers can be traced by enabling a "jose.debug" contextual property: once can see the key encryption algorithm is "A128KW", content encryption algorithm is "A128GCM" and the content type of the encrypted payload is "text/plain".

The following client code can be used to set the client JWE Compact interceptors:

Code Block
languagejava
titleClient JWE SetUp
    public void testJweJwkAesWrap() throws Exception {
        String address = "https://localhost:" + PORT + "/jwejwkaeswrap";
        JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
        bean.setServiceClass(BookStore.class);
        bean.setAddress(address);
        List<Object> providers = new LinkedList<Object>();
        JweWriterInterceptor jweWriter = new JweWriterInterceptor();
        jweWriter.setUseJweOutputStream(true);
        providers.add(jweWriter);
        providers.add(new JweClientResponseFilter());
        bean.setProviders(providers);
        bean.getProperties(true).put("rs.security.encryption.properties",
                                     "org/apache/cxf/systest/jaxrs/security/secret.jwk.properties");
        bean.getProperties(true).put("jose.debug", true);
        BookStore bs = bean.create(BookStore.class);
        String text = bs.echoText("book");
        assertEquals("book", text);
    }

The above code shows a client proxy code but WebClient can be created instead. The server is configured here. The client can be configured in Spring/Blueprint too.

JweJsonWriterInterceptor creates JWE JSON sequences on the client or server out directions. 

JweJsonClientResponseFilter and JweContainerRequestFilter process the incoming client or server JWE JSON sequences.

Here is the same example for encrypting "book" but with JWS JSON interceptors:

No Format
Address: https://localhost:9001/jwejsonhmac/bookstore/books
Http-Method: POST
Content-Type: application/jose+json
Payload: 
{
  "protected" : "eyJlbmMiOiJBMTI4R0NNIiwiY3R5IjoidGV4dC9wbGFpbiIsImFsZyI6IkExMjhLVyJ9",
  "recipients":
   [
     {
       "encrypted_key": "iq1vJBpOHKRkMDoY2GTakWE6M_uPGVsh"
     }
   ],
   "iv":"SUpOEf-7Q1tT0JV_",
   "ciphertext":"alKm_g",
   "tag":"DkW2pZCd7lhR0KqIGQ69-A"
}

Note the Base64Url encoded protected headers go first, followed by the 'recipients' array, with each element containing the encrypted content encryption key which can be decrypted by the recipient private key, with the array of recipients followed by the IV, ciphertext and authentication tag Base64Url sequences.

Linking JWT authentications to JWS or JWE content

CXF introduced a "JWT" HTTP authentication scheme, with a Base64Url encoded JWT token representing a user authentication against an IDP capable of issuing JWT assertions (or simply JWT tokens). JWT assertion is like SAML assertion except that it is in a JSON format. If you'd like to cryptographically bind this JWT token to a data secured by JWS and/or JWE processors then simply add JwtAuthenticationClientFilteron the client side and JwtAuthenticationFilter on the server side. These filters link the authentication token with a randomly generated secure value which is added to both the token and the body JWS/JWE protected headers.

This approach is more effective compared to the ones where the body hash is calculated before it is submitted to a signature creation function, with the signature added as HTTP header.

 

 

Signing and Verification of HTTP Attachments

The signing and verification of HTTP request and response attachments is supported starting from CXF 3.1.12.

This feature does not buffer the request and response attachment data and is completely streaming-'friendly'.

Note that in some cases the data may need to be buffered on the receiver end.

It depends on JWS with Detached Content and  JWS with Unencoded Payload options as well as on the newly introduced CXF multipart filters and works as follows.

When request or response attachment parts are about to be submitted to the Multipart serialization provider, JWS Multipart Output Filter (JwsMultipartClientRequestFilter and/or JwsMultipartContainerResponseFilter) initializes a JWSSignature object. Next every parts's output stream is replaced with the filtering output stream which updates the signature object on every write operation. Finally this multipart filter adds one more attachment part to the list of the attachments to be written - this part holds a reference to JWS Signature. When this last part is written, JWSSignature produces the signature bytes which are encoded using either JWS Compact or JWS JSON format, with the detached and unencoded content already being pushed to the output stream.

When the attachment parts are about to be read by the Multipart deserialization provider, their signature carried over in the last part will need to be verified. Just before the parts are about to be read in order to be made available to the application code, JWS Multipart Input Filter (JwsMultipartContainerRequestFilter and/or JwsMultipartClientResponseFilter) checks the last part and initializes a JWSVerificationSignature object. Next for every attachment but the last one it replaces the input stream with the filtering input stream which updates the signature verification object on every read operation. Once all the data have been read it compares the calculated signature with the received signature.

Note when the attachments are accessed by the receiving application code, the read process will fail to complete if the validation fails. For example, if the application code copies a given part's InputStream to the disk then this copy operation will fail. For example:

Code Block
languagejava
@POST
@Path("/books")
@Consumes("multipart/related")
public void uploadBookMultipart(@Multipart(type = "application/xml") Book book) {
        // This method will not be even invoked if the data signature verification fails 
        // causing the construction of Book bean to fail
}


@POST
@Path("/pdf")
@Consumes("multipart/related")
public void uploadStreamMultipart(@Multipart(type = "application/pdf") InputStream is) {
        OutputStream os = getTargetOutputStream();
        // This copy operation will fail
        IOUtils.copy(is, os); 
}


Note that besides the signature verification process, CXF offers some other indirect support for ensuring the attachment data have not been affected. For example, the size of the attachments can be restricted, and if the data stream is converted from XML then the conversion process will be controlled by the secure XML parser. 

However, if the receiver starts acting immediately on the attachment's InputStream, for example, the attachment data returned from the service to the client are streamed to a UI display which can activate a script then it is important that a 'bufferPayload' property is enabled on either JwsMultipartContainerRequestFilter or JwsMultipartClientResponseFilter. It will ensure that the data streams are validated first before the application gets an access to them.

The 'bufferPayload' property may also need be enabled if the multipart payload contains many attachment parts. In this case, if the receiving code is written to consume all the parts in the order different to the one the parts have been ordered in the multipart payload or if the receiver code may optionally skip reading some of the parts, then the 'bufferPayload' property must be enabled.

Here is an example showing how a Book object (represented as an XML attachment on the wire) can be secured.

Given this client code:

Code Block
languagejava
@Test
public void testJwsJwkBookHMacMultipart() throws Exception {
    String address = "https://localhost:" + PORT + "/jwsjwkhmacSinglePart";
    BookStore bs = createJwsBookStoreHMac(address, true, false);
    Book book = bs.echoBookMultipart(new Book("book", 123L));
    assertEquals("book", book.getName());
    assertEquals(123L, book.getId());
}
private BookStore createJwsBookStoreHMac(String address, 
                                         boolean supportSinglePart,
                                         boolean useJwsJsonSignatureFormat) throws Exception {
     JAXRSClientFactoryBean bean = createJAXRSClientFactoryBean(address, supportSinglePart, 
                                                                   useJwsJsonSignatureFormat);
     bean.getProperties(true).put("rs.security.signature.properties",
         "org/apache/cxf/systest/jaxrs/security/secret.jwk.properties");

     bean.setServiceClass(BookStore.class);
     bean.setAddress(address);
     List<Object> providers = new LinkedList<Object>();
     JwsMultipartClientRequestFilter outFilter = new JwsMultipartClientRequestFilter();
     outFilter.setSupportSinglePartOnly(supportSinglePart);
     outFilter.setUseJwsJsonSignatureFormat(useJwsJsonSignatureFormat);
     providers.add(outFilter);
     JwsMultipartClientResponseFilter inFilter = new JwsMultipartClientResponseFilter();
     inFilter.setSupportSinglePartOnly(supportSinglePart);
     providers.add(inFilter);
     providers.add(new JwsDetachedSignatureProvider());
     bean.setProviders(providers);
     return bean.create(BookStore.class);
}

and the relevant server code:

Code Block
@Path("/bookstore")
public class BookStore {
    
    @POST
    @Path("/books")
    @Produces("multipart/related")
    @Consumes("multipart/related")
    @Multipart(type = "application/xml")
    public Book echoBookMultipart(@Multipart(type = "application/xml") Book book) {
        // This method will not be even invoked if the data signature verification fails 
        return book;
    }
}

and server configuration:

Code Block
languagexml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:jaxrs="http://cxf.apache.org/jaxrs">
    <bean id="serviceBean" class="org.apache.cxf.systest.jaxrs.security.jose.BookStore"/>
    <bean id="jwsInMultipartFilter" class="org.apache.cxf.rs.security.jose.jaxrs.multipart.JwsMultipartContainerRequestFilter"/>
    <bean id="jwsOutMultipartFilter" class="org.apache.cxf.rs.security.jose.jaxrs.multipart.JwsMultipartContainerResponseFilter"/>
    <bean id="jwsDetachedSignatureWriter" class="org.apache.cxf.rs.security.jose.jaxrs.JwsDetachedSignatureProvider"/>
    <jaxrs:server address="https://localhost:${testutil.ports.jaxrs-jws-multipart}/jwsjwkhmacSinglePart">
        <jaxrs:serviceBeans>
            <ref bean="serviceBean"/>
        </jaxrs:serviceBeans>
        <jaxrs:providers>
            <ref bean="jwsInMultipartFilter"/>
            <ref bean="jwsOutMultipartFilter"/>
            <ref bean="jwsDetachedSignatureWriter"/>
        </jaxrs:providers>
        <jaxrs:properties>
            <entry key="rs.security.signature.properties" value="org/apache/cxf/systest/jaxrs/security/secret.jwk.properties"/>
        </jaxrs:properties>
    </jaxrs:server>
</beans

the following request is produced on the wire:

No Format
ID: 1
Address: https://localhost:9001/jwsjwkhmacSinglePart/bookstore/books
Http-Method: POST
Content-Type: multipart/related; type="application/xml"; boundary="uuid:35b4dd32-470d-4f27-b3c2-2c194f924770"; start="<root.message@cxf.apache.org>"
Headers: {Accept=[multipart/related], Connection=[Keep-Alive]}
Payload: 
--uuid:35b4dd32-470d-4f27-b3c2-2c194f924770
Content-Type: application/xml
Content-Transfer-Encoding: binary
Content-ID: <root.message@cxf.apache.org>

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Book><id>123</id><name>book</name></Book>
--uuid:35b4dd32-470d-4f27-b3c2-2c194f924770
Content-Type: application/jose
Content-Transfer-Encoding: binary
Content-ID: <signature>

eyJiNjQiOmZhbHNlLCJjcml0IjpbImI2NCJdLCJhbGciOiJIUzI1NiJ9..LWMjPoronjdGmJFAAIuCc_qh9sI2i5Jc2onBd-fHdMM
--uuid:35b4dd32-470d-4f27-b3c2-2c194f924770--

with the response being formated identically.

Enabling a JWS JSON format will produce a flattened JWS JSON signature in the last part:

No Format
ID: 1
Address: https://localhost:9001/jwsjwkhmacSinglePartJwsJson/bookstore/books
Http-Method: POST
Content-Type: multipart/related; type="application/xml"; boundary="uuid:75b37fab-1745-45b7-93ac-15aa9add9b25"; start="<root.message@cxf.apache.org>"
Headers: {Accept=[multipart/related], Connection=[Keep-Alive]}
Payload: 
--uuid:75b37fab-1745-45b7-93ac-15aa9add9b25
Content-Type: application/xml
Content-Transfer-Encoding: binary
Content-ID: <root.message@cxf.apache.org>

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Book><id>123</id><name>book</name></Book>
--uuid:75b37fab-1745-45b7-93ac-15aa9add9b25
Content-Type: application/jose
Content-Transfer-Encoding: binary
Content-ID: <signature>

{"protected":"eyJiNjQiOmZhbHNlLCJjcml0IjpbImI2NCJdLCJhbGciOiJIUzI1NiJ9","signature":"LWMjPoronjdGmJFAAIuCc_qh9sI2i5Jc2onBd-fHdMM"}
--uuid:75b37fab-1745-45b7-93ac-15aa9add9b25--

JWE

JWE Compact

JweWriterInterceptor creates Compact JWE sequences on the client or server out directions. For example, if you have the client code posting a Book or the server code returning a Book, with this Book representation expected to be encrypted, then add JweWriterInterceptor and set the encryption properties on the JAX-RS client or server.

JweClientResponseFilter and JweContainerRequestFilter process the incoming client or server Compact JWE sequences.

Here is an example of a plain text "book" being encrypted with the A128KW key and A128GCM content encryption (see JWE section above), converted into Compact JWE and POSTed to the target service:

No Format
Address: https://localhost:9001/jwejwkaeswrap/bookstore/books
Http-Method: POST
Content-Type: application/jose
Payload: 
eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4R0NNIiwiY3R5IjoidGV4dC9wbGFpbiJ9.
SQul1USvHmADDLpBvY2Dnqk5GpoowOkJ.
cFuCSzRsl6GZuvHL.
akVT5g.
i8rpTk-v0b1IyE1sVT1IOA

org.apache.cxf.rs.security.jose.common.JoseUtils traceHeaders
INFO: JWE Headers: 
{"alg":"A128KW",
 "enc":"A128GCM",
 "cty":"text/plain"}

You can see 5 JWE parts (put on separate lines for the better readibility) separated by dots. The 1st part is Base64Url encoded protected headers, next one - Base64Url encoded content encryption key, next one - Base64Url encoded IV, next one - Base64Url encoded ciphertext, finally - the authentication tag.

Note that the protected headers can be traced by enabling a "jose.debug" contextual property: once can see the key encryption algorithm is "A128KW", content encryption algorithm is "A128GCM" and the content type of the encrypted payload is "text/plain".

The following client code can be used to set the client JWE Compact interceptors:

Code Block
languagejava
titleClient JWE SetUp
    public void testJweJwkAesWrap() throws Exception {
        String address = "https://localhost:" + PORT + "/jwejwkaeswrap";
        JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
        bean.setServiceClass(BookStore.class);
        bean.setAddress(address);
        List<Object> providers = new LinkedList<Object>();
        JweWriterInterceptor jweWriter = new JweWriterInterceptor();
        jweWriter.setUseJweOutputStream(true);
        providers.add(jweWriter);
        providers.add(new JweClientResponseFilter());
        bean.setProviders(providers);
        bean.getProperties(true).put("rs.security.encryption.properties",
                                     "org/apache/cxf/systest/jaxrs/security/secret.jwk.properties");
        bean.getProperties(true).put("jose.debug", true);
        BookStore bs = bean.create(BookStore.class);
        String text = bs.echoText("book");
        assertEquals("book", text);
    }

The above code shows a client proxy code but WebClient can be created instead. The server is configured here. The client can be configured in Spring/Blueprint too.

JWE JSON

JweJsonWriterInterceptor creates JWE JSON sequences on the client or server out directions. 

JweJsonClientResponseFilter and JweContainerRequestFilter process the incoming client or server JWE JSON sequences.

Here is the same example for encrypting "book" but with JWS JSON interceptors:

No Format
Address: https://localhost:9001/jwejsonhmac/bookstore/books
Http-Method: POST
Content-Type: application/jose+json
Payload: 
{
  "protected" : "eyJlbmMiOiJBMTI4R0NNIiwiY3R5IjoidGV4dC9wbGFpbiIsImFsZyI6IkExMjhLVyJ9",
  "recipients":
   [
     {
       "encrypted_key": "iq1vJBpOHKRkMDoY2GTakWE6M_uPGVsh"
     }
   ],
   "iv":"SUpOEf-7Q1tT0JV_",
   "ciphertext":"alKm_g",
   "tag":"DkW2pZCd7lhR0KqIGQ69-A"
}

Note the Base64Url encoded protected headers go first, followed by the 'recipients' array, with each element containing the encrypted content encryption key which can be decrypted by the recipient private key, with the array of recipients followed by the IV, ciphertext and authentication tag Base64Url sequences.

Linking JWT authentications to JWS or JWE content

CXF introduced a "JWT" HTTP authentication scheme, with a Base64Url encoded JWT token representing a user authentication against an IDP capable of issuing JWT assertions (or simply JWT tokens). JWT assertion is like SAML assertion except that it is in a JSON format. If you'd like to cryptographically bind this JWT token to a data secured by JWS and/or JWE processors then simply add JwtAuthenticationClientFilter on the client side and JwtAuthenticationFilter on the server side. These filters link the authentication token with a randomly generated secure value which is added to both the token and the body JWS/JWE protected headers.

This approach is more effective compared to the ones where the body hash is calculated before it is submitted to a signature creation function, with the signature added as HTTP header.

Note that the "JWT" scheme is not standard, and from CXF 4.0.0 the default scheme has changed to "Bearer".

JWT authorization

CXF supports both role and claims based authorization for JAX-RS endpoints based on information contained in a received JWT. Please see the JAX-RS Token Authorization page for more information.

Optional protection of HTTP headers

Starting from CXF 3.1.12 it is possible to use JWS, JWS JSON, JWE and JWE JSON filters to protect the selected set of HTTP headers. The JOSE payloads produced by these filters guarantee that the JOSE headers are integrity protected. Given this, if one enables a 'protectHttpHeaders' boolean property on the request filters, then, by default, HTTP Content-Type and Accept header values will be registered as JOSE header properties prefixed with "http.", example, "http.Accept":"text/plain". The list of the headers to be protected can be customized using a 'protectedHttpHeaders' set property.

These properties will be compared against the current HTTP headers on the receiving end.

This approach does not prevent the streaming of the outgoing data (which will also be protected by the filters) and offers a way to secure the HTTP headers which are really important for the correct processing of the incoming payloads

JOSE in JAX-RS application code

In some cases you may need to create or process the JOSE data directly in the service or client application code. For example, one of the properties in the request or response payload needs to be JWS signed/verified and/or JWE encrypted/decrypted. The following 2 options can be tried.

Option 1:  Process JOSE directly

This option is about using the CXF JOSE library to sign, encrypt, or/and decrypt and verify the data as documented above. This option should be preferred if one needs to keep a closer control, for example, set the custom JWS or JWE headers, etc.

Option 2:  Use JOSE library helpers and Endpoint Configuration

This option makes it straighforward to do JOSE in the application code. One has to extend or delegate to a specific JOSE helper instance and configure the endpoint with the location of the JOSE properties file where the JWS or JWE algorithm and key store properties are set.

Produce JOSE data

If you need to protect some non JWT property - extend or delegate to JoseProducer:

Code Block
languagejava
import org.apache.cxf.rs.security.jose.common.JoseProducer;
@Path("service")
public class SecureService extends JoseProducer {
    @GET
    public String getProtectedValue() {
        // encrypt and/or sign the data
        return super.processData("some data");
    }
}

// or

@Path("service")
public class SecureService extends AbstractSecureService {
    
    private JoseProducer producer = new JoseProducer();
    @GET
    public String getProtectedValue() {
        // encrypt and/or sign the data
        return producer.processData("some data");
    }
}

If you need to protect some JWT property then extend or delegate to JoseJwtProducer:

Code Block
languagejava
import org.apache.cxf.rs.security.jose.jwt.JoseJwtProducer;
@Path("service")
public class SecureService extends JoseJwtProducer {
    @GET
    public String getProtectedToken() {
        // encrypt and/or sign JWT
        JwtClaims claims = new JwtClaims();
        claims.setIssuer("some issuer");
        // set other claims
        return super.processJwt(new JwtToken(claims));
    }
}

// or

@Path("service")
public class SecureService extends AbstractSecureService {
    
    private JoseJwtProducer producer = new JoseJwtProducer();
    @GET
    public String getProtectedValue() {
        // encrypt and/or sign JWT
        return producer.processJwt(new JwtToken(new JwtClaims()));
    }
}

 In both cases the producer helpers will detect the endpoint specific configuration thus they do not need to be preconfigured - however if needed they have the 'encryptionProvider' and 'signatureProvider' setters which can be used to inject JwsSignatureProvider and/or JweEncryptionProvider instances instead.

The producer helpers require a signature creation only by default. Use their 'setJwsRequired' or 'setJwsRequired' properties to customize it - example, disable JWS but require JWE, or enable JWE to get JWS-protected data encrypted as well.

Consume JOSE data

If you need to decrypt and/or verify some non-JWT JOSE property - extend or delegate to JoseConsumer:

Code Block
languagejava
import org.apache.cxf.rs.security.jose.common.JoseConsumer;
@Path("service")
public class SecureService extends JoseConsumer {
    @POST
    public void acceptProtectedValue(String joseValue) {
        // decrypt the value first if needed, verify the signature
        String data = super.getData(joseValue);
    }
}

// or

@Path("service")
public class SecureService extends AbstractSecureService {
    
    private JoseConsumer consumer = new JoseConsumer();
    @POST
    public void acceptProtectedValue(String joseValue) {
        // decrypt the value first if needed, verify the signature
        String data = consumer.getData(joseValue);
    }
}

If you need to decrypt and/or verify some JWT property then extend or delegate to JoseJwtConsumer:

Code Block
languagejava
import org.apache.cxf.rs.security.jose.jwt.JoseJwtConsumer;
@Path("service")
public class SecureService extends JoseJwtConsumer {
    @POST
    public void acceptProtectedToken(String joseValue) {
        // decrypt the value first if needed, verify the signature
        JwtToken data = super.getJwtToken(joseValue);
    }
}

// or

@Path("service")
public class SecureService extends AbstractSecureService {
    
    private JoseJwtConsumer consumer = new JoseJwtConsumer();
    @POST
    public void acceptProtectedToken(String joseValue) {
        // decrypt the value first if needed, verify the signature
        JwtToken data = consumer.getJwtToken(joseValue);
    }
}

 In both cases the producer helpers will detect the endpoint specific configuration thus they do not need to be preconfigured - however if needed they have the 'jweDecryptor' and 'jwsVerifier' setters which can be used to inject JwsSignatureVerifier and/or JweDecryptionProvider instances instead.

The producer helpers require a signature creation only by default. Use their 'setJwsRequired' or 'setJwsRequired' properties to customize it - example, disable JWS but require JWE, or enable JWE to get JWS-protected data encrypted as well.

Produce and Consume JOSE data

If you need to produce and consumer some non-JWT JOSE properties- extend or delegate to JoseProducerConsumer:

Code Block
languagejava
import org.apache.cxf.rs.security.jose.common.JoseProducerConsumer;
@Path("service")
public class SecureService extends JoseProducerConsumer {
    @POST
    public String echoProtectedValue(String joseValue) {
        // decrypt the value first if needed, verify the signature
        String data = super.getData(joseValue);
        // sign and/or encrypt the data
        return super.processData(data); 
    }
}

// or

@Path("service")
public class SecureService extends AbstractSecureService {
    
    private JoseProducerConsumer jose = new JoseProducerConsumer();
    @POST
    public String echoProtectedValue(String joseValue) {
        // decrypt the value first if needed, verify the signature
        String data = jose.getData(joseValue);
        // sign and/or encrypt the data
        return jose.processData(data); 
    }
}

If you need to decrypt and/or verify some JWT property then extend or delegate to JoseJwtProducerConsumer:

Code Block
languagejava
import org.apache.cxf.rs.security.jose.jwt.JoseJwtProducerConsumer;
@Path("service")
public class SecureService extends JoseJwtProducerConsumer {
    @POST
    public String echoProtectedToken(String joseValue) {
        // decrypt the value first if needed, verify the signature
        JwtToken data = super.getJwtToken(joseValue);
        // sign and/or encrypt the data
        return super.processJwt(data);
    }
}

// or

@Path("service")
public class SecureService extends AbstractSecureService {
    
    private JoseJwtProducerConsumer jose = new JoseJwtProducerConsumer();
    @POST
    public String echoProtectedToken(String joseValue) {
        // decrypt the value first if needed, verify the signature
        JwtToken data = jose.getJwtToken(joseValue);
        // sign and/or encrypt the data
        return jose.processJwt(data);
    }
}

In both cases this composite producer-consumer will use the internal producer and/or consumer helpers which will detect the endpoint specific configuration but which can also be injected with some specific JWE and/or JWS handlers.

Configure the endpoint

These properties will contain a location of the key store, signature and/or encryption algorithm properties, etc. See the Configuration section for all the available configuration options.

Code Block
languagexml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:jaxrs="http://cxf.apache.org/jaxrs">
    <bean id="serviceBean" class="org.apache.cxf.systest.jaxrs.security.jose.SecureService"/>
    <jaxrs:server address="/secure">
        <jaxrs:serviceBeans>
            <ref bean="serviceBean"/>
        </jaxrs:serviceBeans>
        <jaxrs:properties>
            <entry key="rs.security.signature.properties" value="org/apache/cxf/systest/jaxrs/security/secret.jwk.properties"/>
            <entry key="rs.security.encryption.properties" value="org/apache/cxf/systest/jaxrs/security/secret.jwk.properties"/>
         </jaxrs:properties>
    </jaxrs:server>
</beans

Configuration

CXF JOSE configuration provides for loading JWS and JWE keys and supporting various processing options. Configuration properties can be shared between JWS and JWE processors or in/out only JWS and or JWE properties can be set.

...

The above code needs to be executed in the context of the current request (in server or client in/out interceptors or server service code) as it expects the current CXF Message be available in order to deduce where to load the configuration properties from. However JwsUtils and JweUtils provide a number of utility methods for loading the providers without loading the properties first which can be used when setting up the client code or when no properties are available in the current request context. 

When the code needs to load the configuration properties it first looks for the property 'container' file which contains the specific properties instructing which keys and algorithms need to be used. Singature or encryption properties for in/out operations can be provided.  

Configuration Property Containers

Signature

rs.security.signature.out.properties

The signature properties file for Compact or JSON signature creation. If not specified then it falls back to "rs.security.signature.properties".

rs.security.signature.in.properties

The signature properties file for Compact or JSON signature verification. If not specified then it falls back to "rs.security.signature.properties".

rs.security.signature.propertiesThe signature properties file for Compact or JSON signature creation/verification.

Encryption

rs.security.encryption.out.properties

The encryption properties file for Compact or JSON encryption creation. If not specified then it falls back to "rs.security.encryption.properties".

rs.security.encryption.in.properties

The encryption properties file for Compact or JSON decryption. If not specified then it falls back to "rs.security.encryption.properties".

rs.security.encryption.propertiesThe
signature
encryption properties file for encryption/decryption.

Note that these property containers can be used for creating/processing JWS and JWE Compact and JSON sequences. If it is either JWS JSON or JWE JSON and you wish to have more than one signature or encryption be created then let the property value be a commas separated list of locations, with each location pointing to a unique signature or encryption operation property file.

...

Configuration that applies to both encryption and signature

rs.security.keystoreThe Java KeyStore Object to use. This configuration tag is used if you want to pass the KeyStore Object through dynamically.

rs.security.keystore.type

The keystore type. Suitable values are "jks" or "jwk".

rs.security.keystore.passwordThe password required to access the keystore.
rs.security.keystore.alias The keystore alias corresponding to the key to use. You can append one of the following to this tag to get the alias for more specific operations:
     - jwe.out
     - jwe.in
     - jws.out
     - jws.in
rs.security.keystore.aliasesThe keystore aliases corresponding to the keys to use, when using the JSON serialization form. You can append one of the following to this tag to get the alias for more specific operations:
     - jws.out
     - jws.in
rs.security.keystore.fileThe path to the keystore file.
rs.security.key.passwordThe password required to access the private key (in the keystore).
rs.security.key.password.providerA reference to a PrivateKeyPasswordProvider instance used to retrieve passwords to access keys.
rs.security.accept.public.key

Whether to allow using

a JWK received in the header for signature validation

a JWK received in the header for signature validation. The default is "false".

rs.security.enable.revocation CXF 3.4.0Whether to enable revocation or not when validating a certificate chain. The default is "false".

Configuration that applies to signature only

rs.security.signature.key.password.provider

A reference to a PrivateKeyPasswordProvider instance used to retrieve passwords to access keys for signature. If this is not specified it falls back to use "rs.security.key.password.provider".

rs.security.signature.algorithmThe signature algorithm to use. The default algorithm if not specified is 'RS256'.
rs.security.signature.include.public.keyInclude the JWK public key for signature in the "jwk" header.
rs.security.signature.include.certInclude the X.509 certificate for signature in the "x5c" header.
rs.security.signature.include.key.idInclude the JWK key id for signature in the "kid" header.
rs.security.signature.include.cert.sha1Include the X.509 certificate SHA-1 digest for signature in the "x5t" header.
rs.security.signature.include.cert.sha256Include the X.509 certificate SHA-256 digest for signature in the "x5t#S256" header.

Configuration that applies to encryption only

rs.security.decryption.key.password.provider

A reference to a PrivateKeyPasswordProvider instance used to retrieve passwords to access keys for decryption. If this is not specified it falls back to use "rs.security.key.password.provider".

rs.security.encryption.content.algorithmThe encryption content algorithm to use. The default algorithm if not specified is 'A128GCM'.
rs.security.encryption.key.algorithm

The encryption key algorithm to use. The default algorithm if not specified is 'RSA-OAEP' if the key is an RSA key, 'ECDH-ES-A128KW'  if the key is an EC key and 'A128GCMKW' if it is an octet sequence.

rs.security.encryption.zip.algorithmThe encryption zip algorithm to use.
rs.security.encryption.include.public.keyInclude the JWK public key for encryption in the "jwk" header.
rs.security.encryption.include.certInclude the X.509 certificate for encryption in the "x5c" header.
rs.security.encryption.include.key.idInclude the JWK key id for encryption in the "kid" header.
rs.security.encryption.include.cert.sha1Include the X.509 certificate SHA-1 digest for encryption in the "x5t" header.
rs.security.encryption.include.cert.sha256Include the X.509 certificate SHA-256 digest for encryption in the "x5t#S256" header.

Configuration that applies to JWT tokens only

rs.security.enable.unsigned-jwt.principal

Whether to allow unsigned JWT tokens as SecurityContext Principals. The default is false.

expected.claim.audience

Interoperability

...

If this property is defined, the received JWT must have an "aud" claim with a value matching this property.

Interoperability

JOSE is already widely supported in OAuth2 and OIDC applications. Besides that CXF JOSE client or server will interoperate with a 3rd party client/server able to produce or consume JWS/JWE sequences.  For example, see a WebCrypto API use case and  the demo which demonstrates how a JWS sequence produced by a browser-hosted script can be validated by a server application capable of processing JWS, with the demo browser client being tested against a CXF JWS server too. 

 

Third-Party Libraries

Jose4J

Nimbus JOSE