JWS / JWT with Android biometric or PIN prompt

The Android keystore has an API designed to prevent leaks of private keys as well as minimise the risk of unauthorised key use. By creating the key with the setUserAuthenticationRequired(true) option the keystore will require each key signing operation to pass successful authentication (PIN, password, biometric, etc) of the app user. After that the key will be unlocked to complete a single signing. If the signing doesn't take place the key will become disabled after a while.

Support for user authentication when performing JSON Web Signature (JWS) operations was added in v9.4 of Nimbus JOSE+JWT (see ticket).

In order to perform JWS with user authentication the JWSSigner needs to be created with the UserAuthenticationRequired option. During the signing a special exception will get thrown to interrupt the flow and let the app code invoke an authentication prompt and then resume signing by calling a provided Completable interface.

At the time of writing this article the two step signing is available for the JWS RSxxx and PSxx algorithms. File a ticket or submit a PR to add support for the ESxxx family of algorithms.

Example Java code for signing an object with a private RSA key which must be unlocked by the user after successful biometric, PIN or some other authentication mechanism:

import java.security.PrivateKey;
import java.util.*;
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.*;
import com.nimbusds.jose.crypto.opts.*;

// Option to trigger an Android user authentication prompt after the
// signature gets initiated
Set<JWSSignerOption> opts = new HashSet<>();

// Create an RSA signer with a reference to a private RSA 2048-bit key in the
// Android key store
JWSSigner signer = new RSASSASigner(privateKey, opts);

// The payload to sign
Payload payload = new Payload("Hello, world!");

// Create the JWS object
JWSObject jwsObject = new JWSObject(new JWSHeader(JWSAlgorithm.RS256), payload);

// Initiate the signing and watch for a prompt exception
ActionRequiredForJWSCompletionException actionRequired = null;
try {
} catch (ActionRequiredForJWSCompletionException arException) {
    // Copy the exception for processing
    actionRequired = arException;
} catch (JOSEException e) {
    throw new RuntimeException("Internal signing error: " + e.getMessage(), e);

if (actionRequired != null) {
    // Perform user authentication to unlock the private RSA key,
    // e.g. with biometric prompt
    // ...

    // Complete the signing after the RSA key is unlocked

// Output the JWS