8.2. Consuming values from vault

The vault contains sensitive data and Red Hat Single Sign-On treats the secrets accordingly. When accessing a secret, the secret is obtained from the vault and retained in JVM memory only for the necessary time. Then all possible attempts to discard its content from JVM memory is done. This is achieved by using the vault secrets only within try-with-resources statement as outlined below:

    char[] c;
    try (VaultCharSecret cSecret = session.vault().getCharSecret(SECRET_NAME)) {
        // ... use cSecret
        c = cSecret.getAsArray().orElse(null);
        // if c != null, it now contains password
    }

    // if c != null, it now contains garbage

The example uses KeycloakSession.vault() as the entrypoint for accessing the secrets. Using the VaultProvider.obtainSecret method directly is indeed also possible. However the vault() method has the benefit of ability to interpret the raw secret (which is generally a byte array) as a character array (via vault().getCharSecret()) or a String (via vault().getStringSecret()) in addition to obtaining the original uninterpreted value (via vault().getRawSecret() method).

Note that since String objects are immutable, their content cannot be discarded by overriding with random garbage. Even though measures have been taken in the default VaultStringSecret implementation to prevent internalizing Strings, the secrets stored in String objects would live at least to the next GC round. Thus using plain byte and character arrays and buffers is preferrable.