JOSE is a set of high quality specifications that specify how data payloads can be signed/validated and/or encrypted/decrypted with the cryptographic properties set in the JSON-formatted metadata (headers). The data to be secured can be in JSON or other formats (plain text, XML, binary data).
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.
New: Signature and Verification support for multiparts using JWS Detached Content mode.
New: Optional HTTP Header protection.
Having the following dependency will let developers write JOSE JWS or JWE code:
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 BouncyCastle for some of JWE encryption algorithms to be supported:
BouncyCastle provider can be registered and unregistered as follows:
Java and JCE Policy
Java7 or higher is recommended in most cases.
Java6 does not support JWE AES 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), 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).
Java 6 should also be fine but note only CXF 3.0.x can be run with Java 6.
JOSE Overview and Implementation
JOSE consists of the following key parts:
- JWA - JSON Web Algorithms where all supported signature and encryption algorithms are listed
- JWK - JSON Web Keys - introduces a JSON format for describing the public and private keys used by JWA algorithms
- JWS - JSON Web Signature - describes how the data can be signed or validated and introduces compact and JSON JWS formats for representing the signed data
- JWE - JSON Web Encryption - describes how the data can be encrypted or decrypted and introduces compact and JSON JWE formats for representing the encrypted data
Additionally, JWT (JSON Web Token), while technically being not part of JOSE, is often used as an input material to JWS and JWE processors, especially in OAuth2 flows (example: OAuth2 access tokens can be represented internally as JWT, OpenIdConnect IdToken and UserInfo are effectively JWTs). JWT describes how a set of claims in JSON format can be JWS-signed and/or JWE-enctypted.
All JOSE signature and encryption algorithms are grouped and described in the JWA (JSON Web Algorithms) specification.
The algorithms are split into 3 categories: signature algorithms (HMAC, RSA, Elliptic Curve), algorithms for supporting the encryption of content encryption keys (RSA-OAEP, AES Key Wrap, etc), and algorithms for encrypting the actual content (AES GCM or AES CBC HMAC).
All JWS and JWE algorithms process not only the actual data but also the meta-data (the algorithm properties) thus ensuring they are integrity-protected, additionally JWE algorithms produce authentication tags which ensure the already encrypted content won't be manipulated.
Please refer to the specification to get all the information needed (with the follow up links to the corresponding RFC when applicable) about a particular signature or encryption algorithm: the properties, recommended key sizes, other security considerations related to all of or some specific algorithms. CXF JOSE code already enforces a number of the recommended constraints.
CXF offers the utility support for working with JWA algorithms in this package.
Typically one would supply an algorithm property in a type-safe way either to JWS or JWE processor, for example, SignatureAlgorithm.HS256 for JWS, KeyAlgorithm.A256KW plus ContentAlgorithm.A256GCM for JWE, etc. Each enum has methods for checking a key size, JWA and Java JCA algorithm names.
JWK (JSON Web Key) is a JSON document describing the cryptographic key properties. JWKs are very flexible and one can expect JWKs becoming one of the major mechanisms for representing and storing cryptographic keys. While one does not have to represent the keys as JWK in order to sign or encrypt the document and rely on Java JCA secret and asymmetric keys instead, JWK is a preferred representation of signature or encryption keys in JOSE.
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).
A collection of JWK keys is called a JWK Key Set which is represented as JSON array of JWKs.
JWK can contain X509 certificates or their thumbprints if preferred.
CXF offers a utility support for reading and writing JWK keys and key sets and working with the encrypted inlined and standalone JWK stores in this package.
For example, a key set containing public JWK keys can be seen here and referred to from the configuration properties. The private (test) key set can be represented in a clear form, though most likely you'd want a private key set encrypted and referred to like this.
One can inline the encrypted key or the key set directly in the configuration properties. For example, here is how an encrypted single JWK key is inlined. Similarly, here is how an encrypted collection of keys is inlined.
CXF assumes that JWK keys have been encrypted if a password provider is available in a request context, it is typically registered with JAX-RS endpoints. The encryption is done with a password based PBES2 algorithm.
Support for the pluggable strategies for loading JWKs is on the map.
For example, here is how you can load a JWK key using its 'kid':
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.
Signature and Verification Providers
Note the signature and verification capabilities are represented by 2 different interfaces - it was done to keep the interfaces minimalistic and have the concerns separated which can be appreciated most in the cases where the code only signs or only validates.
The following table shows the algorithms and the corresponding providers (org.apache.cxf.rs.security.jose.jws package):
|Algorithm||JWS Header 'alg'||JwsSignatureProvider||JwsSignatureVerifier|
|HMAC||HS256, HS384, HS512|
|RSASSA-PKCS1-v1_5||RS256, RS384, RS512||PrivateKeyJwsSignatureProvider||PublicKeyJwsSignatureVerifier|
|ECDSA||ES256, ES384, ES512||EcDsaJwsSignatureProvider||EcDsaJwsSignatureVerifier|
|RSASSA-PSS||PS256, PS384, PS512||PrivateKeyJwsSignatureProvider||PublicKeyJwsSignatureVerifier|
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.
RS256/384/512 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. 'None' algorithm might be useful when a JWS sequence is subsequently JWE-encrypted or when a 2-way TLS (with client and server certificates) is used.
Once you have decided which algorithm needs to be supported you can initialize an appropriate pair of JwsSignatureProvider and JwsSignatureVerifier if both signing the data and the verification are needed. If only the signing is needed - select JwsSignatureProvider, only the verification - select JwsSignatureVerifier. The selected providers are submitted to JWS Compact or JWS JSON producers or consumers.
JwsUtils utility class has a lot of helper methods to load JwsSignatureProvider or JwsSignatureVerifier and to get JWS sequences created and validated.
JWS Compact representation is the most often used JWS sequence format. It is the concatenation of Base64URL-encoded sequence of JWS headers (algorithm and other properties), Base64URL-encoded sequence of the actual data being protected and Base64URL-encoded sequence of the signature algorithm output bytes.
For example, here is how an Appendix A1 example can be done in CXF:
In the above example, the data (JwtToken) is submitted to an instance of JwsCompactProducer (JwsJwtCompactProducer) and signed with an HMac key.
Here is another example:
In this latest example a plain text sequence is encoded with a private RSA key loaded from the JWK store and validated with a public RSA key loaded from the existing Java JKS store.
While JWS Compact is optimized and represents a concatenation of 3 Base64URL values, JWS JSON is an open JSON container, see Appendix 6.
The most interesting feature of JWS JSON is that allows a content be signed for multiple recipients. For example, the immediate consumer will validate a signature with one key, forward the payload to the next consumer which will also validate the content with another key, etc.
The above code produces a JWS JSON sequence containing two signatures, similarly to this example. If the sequence contains a single signature only then the JWS JSON 'signatures' array will contain a single 'signature' element, or the whole sequence can be flattened instead with the actual 'signatures' array dropped. JwsJsonProducer does not produce the flattened sequence when only a single signature is used by default because 3rd party JWS JSON consumers may only be able to process the sequences with the 'signatures' array, so pass a 'supportFlattened' flag to JwsJsonProducer if needed.
Does it make sense to use JWS JSON if you do not plan to do multiple signatures ? Indeed, if it is only a single signature then using JWS Compact is a good alternative, likely to be used most often.
However, even if you do a single signature, you may still want to try JWS JSON because is is easier to observe the individual JWS JSON structure parts when, example, checking the logs or TCP-tracing HTTP requests/responses. This is especially true when we start talking about an unencoded payload option, see below.
JWS with Detached Content
JWS with 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
By default, JWS Compact and JWS JSON sequences have the data first Base64Url encoded and then inlined in the resulting sequence. This is useful especially for JWS Compact which is used in OAuth2/OIDC flows to represent the signed access or id tokens.
One concern around the data being inlined is that it takes an extra time to Base64Url encode them which may become noticeable with large payloads, and another one is that one can not see the data while looking at JWS sequences in the logs or trace screens.
Thus a JWS with Unencoded Payload option (JWS header 'b64' property set to false) has been introduced to let users configure JWS Signature providers not to encode the actual data payload, see this example.
Both JWS JSON and JWS Compact support 'b64' property for the detached and embedded payloads.
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:
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 (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.
Key and Content Encryption Providers
JWE Encryption process typically involves a content-encryption key being generated with this key being subsequently encrypted/wrapped with a key known to the consumer. Thus CXF offers the providers for supporting the key-encryption algorithms and providers for supporting the content-encryption algorithms. Direct key encryption (where the content-encryption key is established out of band) is also supported.
The following table shows the key encryption algorithms and the corresponding providers (org.apache.cxf.rs.security.jose.jwe package):
|Algorithm||JWE Header 'alg'||KeyEncryptionProvider||KeyDecryptionProvider|
|AES Key Wrap|
A128KW, A192KW, A256KW
|ECDH-ES Key Wrap|
ECDH-ES+A128KW (+A192KW, +256KW)
|AES-GCM Key Wrap|
A128GCMKW, A192GCMKW, A256GCMKW
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.
The following table shows the content encryption algorithms and the corresponding providers:
|Algorithm||JWE Header 'enc'||ContentEncryptionProvider||ContentDecryptionProvider|
A128GCM, A92GCM, A256GCM
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.
JweEncryption and JweDecryption help with creating and processing JWE Compact sequences (see the next section). JweEncryption can also help with streaming JWE JSON sequences (see JAX-RS JWE filters section).
Note that AesCbcHmacJweEncryption and AesCbcHmacJweDecryption providers supporting AES_CBC_HMAC_SHA2 contet encryption are extending JweEncryption and JweDecryption respectively. They implement the content encryption internally but do accept preferred key encryption/decryption providers.
JweUtils utility class has a lot of helper methods to load key and and content encryption providers and get the data encrypted and decrypted.
JWE Compact representation is the most often used JWE sequence format. It is the concatenation of 5 parts: Base64URL-encoded sequence of JWE headers (algorithm and other properties), Base64URL-encoded sequence of JWE encryption key (empty in case of the direct encryption), Base64URL-encoded sequence of JWE Initialization vector, Base64URL-encoded sequence of the produced ciphertext (encrypted data) and finally Base64URL-encoded sequence of the authentication tag (integrity protection for the headers and the ciphertext itself).
JweCompactProducer and JweCompactConsumer offer a basic support for creating and consuming compact JWE sequences. In most cases you will likely prefer to use JweEncryption and JweDecryption instead: JweEncryption uses JweCompactProducer internally when its encrypt method is called (getEncryptedOutput will be discussed in the JAX-RS JWE filters section), and JweDecryption accepts only JWE Compact and uses JweCompactConsumer internally.
Here is the example of doing AES Key Wrap and AES CBC HMAC in CXF:
Here is another example using RSA-OAEP key encryption and AES-GCM content encryption:
While JWE Compact is optimized and represents a concatenation of 5 Base64URL values, JWE JSON is an open JSON container, see Appendix A4.
The most interesting feature of JWE JSON is that allows a content be encrypted by multiple key encryption keys, with te resulting sequence targeted at multiple recipients. For example, the immediate consumer will decrypt the content with its own key decryption key, forward the payload to the next consumer, etc.
Here is the code example:
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:
would expect JWS and/or JWE processing done before the resource method is invoked or after this method returned some response.
This is what CXF JOSE JAX-RS filters do, they help the client or server code get the application data JWS- or JWE-secured. The filters do it by loadng the configuration properties as described below in the Configuration section, and produce or consume JWS or JWE sequences.
Note, JWS Compact and JSON, as well as JWE Compact client and server output filters can do the best effort at keeping the streaming process going while they are signing or encrypting the payload. JWE JSON client/server output filter and JWS Compact client/server input filters will be enhanced in due time to support the streaming too. Most of CXF JOSE system tests enable the streaming capable filters to stream.
JWS and JWE JSON input filters are expected to process JSON containers with the properties set in a random order hence by default they wil not stream the data in.
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.
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.
Here is an example of a JSON Book representation being HS256 signed and converted into Compact JWS and POSTed to the target service:
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.
Note that the protected headers can be traced by enabling a "jose.debug" contextual property: once can see the signature algorithm is "HS256" and the content type of the signed payload is "json" which is a shorcut for a content type "application/json" where "application" is omitted.
The following client code can be used to set the client JWS Compact interceptors:
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 Unencoded Payload above for restrictions).
Here is an example of a plain text "book" being HS256-signed, converted into JWS Compact and POSTed to the target service:
Note that a 2nd part, "book", is not Base64Url encoded. Set an 'encodePayload' option on the request or response JWS Compact filter to 'false'.
JwsJsonWriterInterceptor creates JWS JSON sequences on the client or server out directions.
Here is an example of a plain text "book" being HS256-signed, converted into JWS JSON and POSTed to the target service:
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 unencoded JWS payload option will produce:
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
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.
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:
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:
and the relevant server code:
and server configuration:
the following request is produced on the wire:
with the response being formated identically.
Enabling a JWS JSON format will produce a flattened JWS JSON signature in the last part:
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.
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:
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:
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.
Here is the same example for encrypting "book" but with JWS JSON interceptors:
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".
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:
If you need to protect some JWT property then extend or delegate to JoseJwtProducer:
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:
If you need to decrypt and/or verify some JWT property then extend or delegate to JoseJwtConsumer:
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:
If you need to decrypt and/or verify some JWT property then extend or delegate to JoseJwtProducerConsumer:
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.
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.
Typically a secure JAX-RS endpoint or client is initialized with JWS and or JWE properties.
For example, this endpoint is configured with a single JWS properties file which will apply to both input (signature verification) and output (signature creation) JWS operations. This endpoint depends on two JWS properties files, one - for input JWS, another one - for output JWS. Similarly, this endpoint uses a single JWE properties file for encrypting/decrypting the data, while this endpoint uses two JWE properties files. This endpoint support both JWS and JSON with in/out specific properties. If either JWS or JWE private key needs to be loaded from the password-protected storage (JKS, encryped JWK) then a password provider needs be registered as well, it can be shared between JWS or JWS or be in/out specific for either JWS or JWE.
These configuration propertie are of major help when JAX-RS JOSE filters process the in/out payload without the application service code being aware of it. While filters can be injected with JWS or JWE providers directly, one would usually set the relevant properties as part of the endpoint or client set-up and expect the filters load the required JWS or JWE providers as needed.
If you need to do JWS or JWE processing directly in your service or interceptor code then having the properties may also be helpful, for example, the following code works because it is indirectly supported by the properties indicating which signature or encryption algorithm is used, where to get the key if needed, etc:
The providers may be initialized from a single properties file or each of them may have specific properties allocated to it.
Sometimes it can be useful to load the properties only and check the signature or encryption algorithm and load a JWS or JWE provider directly as shown in JWS and JWE sections above.
After loading the properties one can check various property values (signature algorithm, etc) and use it to create a required provider.
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
The signature properties file for Compact or JSON signature creation. If not specified then it falls back to "rs.security.signature.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.properties||The signature properties file for Compact or JSON signature creation/verification.|
The encryption properties file for Compact or JSON encryption creation. If not specified then it falls back to "rs.security.encryption.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.properties||The 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.
Once the properties are loaded the runtime proceeds with initializing JWS/JWE providers accordingly. The following section lists the properties, some oif them being common and some - unique to the signature/verification and encryption/decryption processes.
Note that one can override some of the properties, for example, 'rs.security.store' can be set as a dynamic request property pointing to a preloaded Java KeyStore object.
Configuration that applies to both encryption and signature
|rs.security.keystore||The Java KeyStore Object to use. This configuration tag is used if you want to pass the KeyStore Object through dynamically.|
The keystore type. Suitable values are "jks" or "jwk".
|rs.security.keystore.password||The 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:|
|rs.security.keystore.aliases||The 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:|
|rs.security.keystore.file||The path to the keystore file.|
|rs.security.key.password||The password required to access the private key (in the keystore).|
|rs.security.key.password.provider||A reference to a PrivateKeyPasswordProvider instance used to retrieve passwords to access keys.|
Whether to allow using a JWK received in the header for signature validation. The default is "false".
|rs.security.enable.revocation CXF 3.4.0||Whether to enable revocation or not when validating a certificate chain. The default is "false".|
Configuration that applies to signature only
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.algorithm||The signature algorithm to use. The default algorithm if not specified is 'RS256'.|
|rs.security.signature.include.public.key||Include the JWK public key for signature in the "jwk" header.|
|rs.security.signature.include.cert||Include the X.509 certificate for signature in the "x5c" header.|
|rs.security.signature.include.key.id||Include the JWK key id for signature in the "kid" header.|
|rs.security.signature.include.cert.sha1||Include the X.509 certificate SHA-1 digest for signature in the "x5t" header.|
|rs.security.signature.include.cert.sha256||Include the X.509 certificate SHA-256 digest for signature in the "x5t#S256" header.|
Configuration that applies to encryption only
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.algorithm||The encryption content algorithm to use. The default algorithm if not specified is 'A128GCM'.|
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.algorithm||The encryption zip algorithm to use.|
|rs.security.encryption.include.public.key||Include the JWK public key for encryption in the "jwk" header.|
|rs.security.encryption.include.cert||Include the X.509 certificate for encryption in the "x5c" header.|
|rs.security.encryption.include.key.id||Include the JWK key id for encryption in the "kid" header.|
|rs.security.encryption.include.cert.sha1||Include the X.509 certificate SHA-1 digest for encryption in the "x5t" header.|
|rs.security.encryption.include.cert.sha256||Include the X.509 certificate SHA-256 digest for encryption in the "x5t#S256" header.|
Configuration that applies to JWT tokens only
Whether to allow unsigned JWT tokens as SecurityContext Principals. The default is false.
|expected.claim.audience||If this property is defined, the received JWT must have an "aud" claim with a value matching this property.|
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.