### Use VaultKeyValueOperations with KV_1 backend Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Shows how to obtain VaultKeyValueOperations for the Key-Value version 1 backend and perform put and get operations. The example uses the 'secret' mount path and KV_1 backend. Note that the get operation retrieves the 'social-security-number' key, but the put operation stores a 'password' key, which may be a discrepancy in the source. ```java VaultOperations operations = new VaultTemplate(new VaultEndpoint()); VaultKeyValueOperations keyValueOperations = operations.opsForKeyValue("secret", VaultKeyValueOperationsSupport.KeyValueBackend.KV_1); keyValueOperations.put("elvis", Collections.singletonMap("password", "409-52-2002")); VaultResponse read = keyValueOperations.get("elvis"); read.getRequiredData().get("social-security-number"); ``` -------------------------------- ### VaultBytesKeyGenerator example Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Creates a VaultBytesKeyGenerator with VaultOperations and generates a random key using Vault's transit backend. ```java VaultOperations operations = …; VaultBytesKeyGenerator generator = new VaultBytesKeyGenerator(operations); byte[] key = generator.generateKey(); ``` -------------------------------- ### VaultBytesEncryptor example Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Creates a VaultBytesEncryptor with VaultTransitOperations and a key name, then encrypts and decrypts data using Vault's transit backend. ```java VaultTransitOperations transit = …; VaultBytesEncryptor encryptor = new VaultBytesEncryptor(transit, "my-key-name"); byte[] ciphertext = encryptor.encrypt(plaintext); byte[] result = encryptor.decrypt(ciphertext); ``` -------------------------------- ### Use VaultKeyValueOperations with KV version 2 Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Shows how to obtain VaultKeyValueOperations for the KV version 2 backend and perform basic put and get operations. The example uses the 'secret' mount and stores a simple map as the secret data. ```java VaultOperations operations = new VaultTemplate(new VaultEndpoint()); VaultKeyValueOperations keyValueOperations = operations.opsForKeyValue("secret", VaultKeyValueOperationsSupport.KeyValueBackend.KV_2); keyValueOperations.put("elvis", Collections.singletonMap("social-security-number", "409-52-2002")); VaultResponse read = keyValueOperations.get("elvis"); read.getRequiredData().get("social-security-number"); ``` -------------------------------- ### Initialize Vault using doWithVault callback Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Uses the doWithVault execution callback on ReactiveVaultOperations to compose a reactive sequence with the WebClient, allowing interaction with Vault without a session context. The example sends a PUT request to /sys/init with a request body and retrieves a VaultInitializationResponse entity. ```java reactiveVaultOperations.doWithVault(webClient -> { return webClient.put() .uri("/sys/init") .syncBody(request) .retrieve() .toEntity(VaultInitializationResponse.class); }); ``` -------------------------------- ### SslConfiguration examples Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Shows how to configure SSL for Spring Vault using SslConfiguration. The first line creates a full configuration with trust store and key store. The subsequent lines show variants for trust store only, key store only, and key store with key configuration. Note: SslConfiguration is only applied when Apache Http Components or OkHttp is on the classpath. ```java SslConfiguration sslConfiguration = SslConfiguration.create( __**(1)** new FileSystemResource("client-cert.jks"), "changeit".toCharArray(), new FileSystemResource("truststore.jks"), "changeit".toCharArray()); SslConfiguration.forTrustStore(new FileSystemResource("keystore.jks"), __**(2)** "changeit".toCharArray()) SslConfiguration.forKeyStore(new FileSystemResource("keystore.jks"), __**(3)** "changeit".toCharArray()) SslConfiguration.forKeyStore(new FileSystemResource("keystore.jks"), __**(4)** "changeit".toCharArray(), KeyConfiguration.of("key-password".toCharArray(), "my-key-alias")) ``` -------------------------------- ### Example application using Spring Vault Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Main application that uses VaultTemplate to write, read, and delete a secret. Requires Vault to be configured with a root token of 00000000-0000-0000-0000-000000000000. Demonstrates instantiating VaultTemplate without a Spring context. ```java package org.springframework.vault.example; import org.springframework.vault.authentication.TokenAuthentication; import org.springframework.vault.client.VaultEndpoint; import org.springframework.vault.core.VaultTemplate; import org.springframework.vault.support.VaultResponseSupport; public class VaultApp { public static void main(String[] args) { VaultTemplate vaultTemplate = new VaultTemplate(new VaultEndpoint(), new TokenAuthentication("00000000-0000-0000-0000-000000000000")); Secrets secrets = new Secrets(); secrets.username = "hello"; secrets.password = "world"; vaultTemplate.write("secret/myapp", secrets); VaultResponseSupport response = vaultTemplate.read("secret/myapp", Secrets.class); System.out.println(response.getData().getUsername()); vaultTemplate.delete("secret/myapp"); } } ``` -------------------------------- ### AppRole Authentication Flow with AuthenticationSteps Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Declares a multi-step authentication flow starting from a Supplier that provides the login state, then posts it to Vault for token creation. Template variables in the login path are subject to URL escaping. ```java AuthenticationSteps.fromSupplier( __**(1)** () -> getAppRoleLogin(options.getRoleId(), options.getSecretId())) __**(2)** .login("auth/{mount}/login", options.getPath()); __**(3)** ``` -------------------------------- ### Use VaultVersionedKeyValueOperations for versioned secrets Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Demonstrates the versioned Key-Value API for storing, retrieving specific versions, mapping to value objects, and using check-and-set operations. The example shows how to store a secret, obtain its version, retrieve a specific version, map to a custom class, and update using a versioned input. ```java VaultOperations operations = new VaultTemplate(new VaultEndpoint()); VaultVersionedKeyValueOperations versionedOperations = operations.opsForVersionedKeyValue("secret"); Versioned.Metadata metadata = versionedOperations.put("elvis", __**(1)** Collections.singletonMap("social-security-number", "409-52-2002")); Version version = metadata.getVersion(); __**(2)** Versioned ssn = versionedOperations.get("elvis", Version.from(42)); __**(3)** Versioned mappedSsn = versionedOperations.get("elvis", __**(4)** Version.from(42), SocialSecurityNumber.class); Versioned> versioned = Versioned.create(Collections __**(5)** .singletonMap("social-security-number", "409-52-2002"), Version.from(42)); versionedOperations.put("elvis", version); ``` -------------------------------- ### Use VaultTemplate directly with KV v2 Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Shows direct interaction with the KV version 2 backend using VaultTemplate. It demonstrates writing and reading secrets, requiring the 'data/' path segment and wrapping the data in a 'data' map. The example reads a secret and extracts the data field. ```java VaultOperations operations = new VaultTemplate(new VaultEndpoint()); operations.write("secret/data/elvis", Collections.singletonMap("data", Collections.singletonMap("social-security-number", "409-52-2002"))); VaultResponse read = operations.read("secret/data/ykey"); Map data = (Map) read.getRequiredData().get("data"); data.get("social-security-number"); ``` -------------------------------- ### Example JSON structure of properties stored in Vault Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Shows the expected JSON structure with a nested 'data' element containing properties like 'database.password' and 'user.name'. ```json { // … "data": { "database": { "password": ... }, "user.name": ..., } // … } ``` -------------------------------- ### Registering Spring Vault objects using Java based bean metadata Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Extend AbstractReactiveVaultConfiguration and implement vaultEndpoint() and clientAuthentication() to configure a Vault connection. The sample uses TokenAuthentication for quick start; consider a more secure method for production. ```java @Configuration public class AppConfig extends AbstractReactiveVaultConfiguration { /** * Specify an endpoint for connecting to Vault. */ @Override public VaultEndpoint vaultEndpoint() { return new VaultEndpoint(); __**(1)** } /** * Configure a client authentication. * Please consider a more secure authentication method * for production use. */ @Override public ClientAuthentication clientAuthentication() { return new TokenAuthentication("…"); __**(2)** } } ``` -------------------------------- ### Registering Spring Vault objects using Java based bean metadata Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Extend AbstractVaultConfiguration and implement vaultEndpoint() and clientAuthentication(). Uses TokenAuthentication for quick start; VaultEndpoint defaults to https://localhost:8200. ```java @Configuration public class AppConfig extends AbstractVaultConfiguration { /** * Specify an endpoint for connecting to Vault. */ @Override public VaultEndpoint vaultEndpoint() { return new VaultEndpoint(); __**(1)** } /** * Configure a client authentication. * Please consider a more secure authentication method * for production use. */ @Override public ClientAuthentication clientAuthentication() { return new TokenAuthentication("…"); __**(2)** } } ``` -------------------------------- ### Synchronous AuthenticationSteps Execution with CubbyholeAuthentication Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Shows how to create AuthenticationSteps from CubbyholeAuthentication options and execute them synchronously using AuthenticationStepsExecutor to obtain a VaultToken. ```java CubbyholeAuthenticationOptions options = … RestOperations restOperations = … AuthenticationSteps steps = CubbyholeAuthentication.createAuthenticationSteps(options); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(steps, restOperations); VaultToken token = executor.login(); ``` -------------------------------- ### Custom AppIdUserIdMechanism implementation Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Example of a custom AppIdUserIdMechanism that must implement the createUserId method. Spring Vault calls this method each time it authenticates using AppId. ```java public class MyUserIdMechanism implements AppIdUserIdMechanism { @Override public String createUserId() { String userId = … return userId; } } ``` -------------------------------- ### Sample Repository Query Method (findByIdStartsWith) Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Defines a repository interface extending CrudRepository with a query method that finds credentials by ID prefix. Vault query methods only support predicates on the @Id property. ```java public interface CredentialsRepository extends CrudRepository { List findByIdStartsWith(String prefix); } ``` -------------------------------- ### Access to Person Entities - CRUD Operations Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Example of injecting CredentialsRepository and performing save, findOne, count, and delete operations. The save operation stores properties under key 'credentials/heisenberg' in the generic secret backend. ```java @Autowired CredentialsRepository repo; public void basicCrudOperations() { Credentials creds = new Credentials("heisenberg", "327215", "AAA-GG-SSSS"); rand.setAddress(new Address("308 Negra Arroyo Lane", "Albuquerque", "New Mexico", "87104")); repo.save(creds); __**(1)** repo.findOne(creds.getId()); __**(2)** repo.count(); __**(3)** repo.delete(creds); __**(4)** } ``` -------------------------------- ### Configure PCF authentication with PcfAuthenticationOptions Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Configure Vault authentication using PCF instance credentials. Requires the BouncyCastle library for RSA-PSS signatures. Instance credentials are read from CF_INSTANCE_CERT and CF_INSTANCE_KEY. ```java @Configuration class AppConfig extends AbstractVaultConfiguration { // … @Override public ClientAuthentication clientAuthentication() { PcfAuthenticationOptions options = PcfAuthenticationOptions.builder() .role(…).build(); PcfAuthentication authentication = new PcfAuthentication(options, restOperations()); } // … } ``` -------------------------------- ### Configure TLS Certificate Authentication with ClientCertificateAuthentication Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Enable 'cert' authentication by configuring a Java Keystore with the client certificate and private key, and override clientAuthentication() in a class extending AbstractVaultConfiguration. Uses ClientCertificateAuthenticationOptions with a path and ClientCertificateAuthentication with restOperations(). ```java @Configuration class AppConfig extends AbstractVaultConfiguration { // … @Override public ClientAuthentication clientAuthentication() { ClientCertificateAuthenticationOptions options = ClientCertificateAuthenticationOptions.builder() .path(…).build(); return new ClientCertificateAuthentication(options, restOperations()); } // … } ``` -------------------------------- ### Java-based configuration class using EnvironmentVaultConfiguration Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Use @PropertySource to load vault.properties and @Import(EnvironmentVaultConfiguration.class) to enable Vault configuration from environment properties. ```java @PropertySource("vault.properties") @Import(EnvironmentVaultConfiguration.class) public class MyConfiguration{ } ``` -------------------------------- ### Create and Store Tokens with Vault CLI Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Creates tokens and stores one in the cubbyhole secret backend. The first command creates a token, the second creates a token with options, and the third exports the token and writes it to cubbyhole/token. ```shell $ vault token create Key Value --- ----- token f9e30681-d46a-cdaf-aaa0-2ae0a9ad0819 token_accessor 4eee9bd9-81bb-06d6-af01-723c54a72148 token_duration 0s token_renewable false token_policies [root] $ vault token create -use-limit=2 -orphan -no-default-policy -policy=none Key Value --- ----- token 895cb88b-aef4-0e33-ba65-d50007290780 token_accessor e84b661c-8aa8-2286-b788-f258f30c8325 token_duration 0s token_renewable false token_policies [none] $ export VAULT_TOKEN=895cb88b-aef4-0e33-ba65-d50007290780 $ vault write cubbyhole/token token=f9e30681-d46a-cdaf-aaa0-2ae0a9ad0819 ``` -------------------------------- ### Sign and Verify Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Creates an asymmetric key, signs a plaintext message, and verifies the signature. ```APIDOC ## Sign and Verify ### Description Creates an asymmetric key, signs a plaintext message, and verifies the signature. ### Method N/A (SDK method) ### Endpoint N/A (SDK method) ### Parameters - **keyName** (String) - Required - The name of the signing key. - **keyType** (String) - Required - The type of asymmetric key (e.g., "ed25519"). - **plaintext** (byte[]) - Required - The plaintext message to sign. - **signature** (Signature) - Required - The signature object to verify. ### Request Example ```java byte[] plaintext = "plaintext to sign".getBytes(); transitOperations.createKey("my-ed25519-key", VaultTransitKeyCreationRequest.ofKeyType("ed25519")); Signature signature = transitOperations.sign("my-ed25519-key", Plaintext.of(plaintext)); boolean valid = transitOperations.verify("my-ed25519-key", Plaintext.of(plaintext), signature); ``` ### Response #### Success Response - **signature** (Signature) - The generated signature. - **valid** (boolean) - Whether the signature is valid. #### Response Example ```java Signature signature = ...; boolean valid = true; ``` ``` -------------------------------- ### Initialize Vault with doWithVault and RestOperationsCallback Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Uses VaultOperations.doWithVault with a RestOperationsCallback to send a PUT request to /sys/init and return the VaultInitializationResponse. This callback allows interaction with Vault without requiring a session. ```java vaultOperations.doWithVault(new RestOperationsCallback() { @Override public VaultInitializationResponse doWithRestOperations(RestOperations restOperations) { ResponseEntity exchange = restOperations .exchange("/sys/init", HttpMethod.PUT, new HttpEntity(request), VaultInitializationResponse.class); return exchange.getBody(); } }); ``` -------------------------------- ### Configure token authentication Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Configure token authentication by returning a TokenAuthentication instance from clientAuthentication(). Token authentication is the default method and requires a static token. ```java @Configuration class AppConfig extends AbstractVaultConfiguration { // … @Override public ClientAuthentication clientAuthentication() { return new TokenAuthentication("…"); } // … } ``` -------------------------------- ### Transit Backend: Create Key, Encrypt, and Decrypt Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Shows how to use VaultTransitOperations to create a key of type 'aes128-gcm96', encrypt a plaintext string, and decrypt the resulting ciphertext. The transit engine provides cryptographic functions without storing data. ```java VaultOperations operations = new VaultTemplate(new VaultEndpoint()); VaultTransitOperations transitOperations = operations.opsForTransit("transit"); transitOperations.createKey("my-aes-key", VaultTransitKeyCreationRequest.ofKeyType("aes128-gcm96")); __**(1)** String ciphertext = transitOperations.encrypt("my-aes-key", "plaintext to encrypt"); __**(2)** String plaintext = transitOperations.decrypt("my-aes-key", ciphertext); __**(3)** ``` -------------------------------- ### Token Management: Create, Renew, and Revoke Tokens Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Shows how to use VaultTokenOperations to create a token with default settings, create a token with a custom request (policy, display name, renewable, TTL), renew a token, and revoke a token. The token operations are typically used by SessionManager for session token management. ```java VaultOperations operations = new VaultTemplate(new VaultEndpoint()); VaultTokenOperations tokenOperations = operations.opsForToken(); VaultTokenResponse tokenResponse = tokenOperations.create(); __**(1)** VaultToken justAToken = tokenResponse.getToken(); VaultTokenRequest tokenRequest = VaultTokenRequest.builder().withPolicy("policy-for-myapp") .displayName("Access tokens for myapp") .renewable() .ttl(Duration.ofHours(1)) .build(); VaultTokenResponse appTokenResponse = tokenOperations.create(tokenRequest); __**(2)** VaultToken appToken = appTokenResponse.getToken(); tokenOperations.renew(appToken); __**(3)** tokenOperations.revoke(appToken); __**(4)** ``` -------------------------------- ### Issue and revoke certificates with VaultPkiOperations Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Shows the full workflow: build a VaultCertificateRequest, issue a certificate from the 'pki' mount, access the CertificateBundle as a KeyStore or via JCE, and revoke the certificate by serial number. Requires a configured VaultTemplate and a running Vault PKI secrets engine. ```java VaultOperations operations = new VaultTemplate(new VaultEndpoint()); VaultPkiOperations pkiOperations = operations.opsForPki("pki"); VaultCertificateRequest request = VaultCertificateRequest.builder() __**(1)** .ttl(Duration.ofHours(48)) .altNames(Arrays.asList("prod.dc-1.example.com", "prod.dc-2.example.com")) .withIpSubjectAltName("1.2.3.4") .commonName("hello.example.com") .build(); VaultCertificateResponse response = pkiOperations.issueCertificate("production", request); __**(2)** CertificateBundle certificateBundle = response.getRequiredData(); KeyStore keyStore = certificateBundle.createKeyStore("my-keystore"); __**(3)** KeySpec privateKey = certificateBundle.getPrivateKeySpec(); __**(4)** X509Certificate certificate = certificateBundle.getX509Certificate(); X509Certificate caCertificate = certificateBundle.getX509IssuerCertificate(); pkiOperations.revoke(certificateBundle.getSerialNumber()); __**(5)** ``` -------------------------------- ### Transit Backend - Cryptographic Operations Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Shows how to create keys, encrypt, and decrypt data using Spring Vault's VaultTransitOperations. ```APIDOC ## Transit Backend ### Description This backend handles cryptographic functions on data in-transit, including encryption, decryption, key creation, and more. It acts as 'cryptography as a service'. ### Operations - **createKey(String name, VaultTransitKeyCreationRequest request)** - Creates a key with specified type. - **encrypt(String keyName, String plaintext)** - Encrypts plaintext using the specified key. - **decrypt(String keyName, String ciphertext)** - Decrypts ciphertext using the specified key. ### Example ```java VaultOperations operations = new VaultTemplate(new VaultEndpoint()); VaultTransitOperations transitOperations = operations.opsForTransit("transit"); transitOperations.createKey("my-aes-key", VaultTransitKeyCreationRequest.ofKeyType("aes128-gcm96")); String ciphertext = transitOperations.encrypt("my-aes-key", "plaintext to encrypt"); String plaintext = transitOperations.decrypt("my-aes-key", ciphertext); ``` ### Parameters - **keyName** (String) - Required - The name of the key to use. - **plaintext** (String) - Required - The data to encrypt. - **ciphertext** (String) - Required - The encrypted data to decrypt. - **VaultTransitKeyCreationRequest** (object) - Required - Request containing key type. ### Return Values - **String** - For encrypt: ciphertext; for decrypt: plaintext. ``` -------------------------------- ### Create Wrapped Token with Vault CLI Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Creates a wrapped token using 'vault token-create -wrap-ttl="10m"'. Requires Vault 0.6.0 or higher. The output shows the wrapping token and related fields. ```shell $ vault token-create -wrap-ttl="10m" Key Value --- ----- wrapping_token: 397ccb93-ff6c-b17b-9389-380b01ca2645 wrapping_token_ttl: 0h10m0s wrapping_token_creation_time: 2016-09-18 20:29:48.652957077 +0200 CEST wrapped_accessor: 46b6aebb-187f-932a-26d7-4f3d86a68319 ``` -------------------------------- ### Configure Kubernetes Authentication with KubernetesAuthenticationOptions Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Configures Kubernetes authentication by providing a role and JWT supplier. Requires a Kubernetes Service Account Token, usually mounted at /var/run/secrets/kubernetes.io/serviceaccount/token. The role name is mandatory. ```java @Configuration class AppConfig extends AbstractVaultConfiguration { // … @Override public ClientAuthentication clientAuthentication() { KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder() .role(…).jwtSupplier(…).build(); return new KubernetesAuthentication(options, restOperations()); } // … } ``` -------------------------------- ### Stored Token Authentication Flow with AuthenticationSteps Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Creates a single-step authentication flow from a VaultToken using AuthenticationSteps.just(). This is the simplest form of an authentication flow. ```java AuthenticationSteps.just(VaultToken.of(…)); ``` -------------------------------- ### Configure GCP-GCE authentication with GcpComputeAuthenticationOptions Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Configure Vault authentication using GCP Compute Engine instance identity. Requires GcpComputeAuthenticationOptions and restOperations(). ```java @Configuration class AppConfig extends AbstractVaultConfiguration { // … @Override public ClientAuthentication clientAuthentication() { GcpComputeAuthenticationOptions options = GcpComputeAuthenticationOptions.builder() .role(…).build(); GcpComputeAuthentication authentication = new GcpComputeAuthentication(options, restOperations()); } // … } ``` -------------------------------- ### Sign and verify plain text with ed25519 key Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Create an asymmetric key, sign a plain text message, and verify the signature. The createKey method requires a key name and a VaultTransitKeyCreationRequest with the key type. The sign method returns a Signature object, and the verify method checks the signature against the plain text, returning a boolean. ```java byte [] plaintext = "plaintext to sign".getBytes(); transitOperations.createKey("my-ed25519-key", VaultTransitKeyCreationRequest.ofKeyType("ed25519")); __**(1)** Signature signature = transitOperations.sign("my-ed25519-key", Plaintext.of(plaintext)); __**(2)** boolean valid = transitOperations.verify("my-ed25519-key", Plaintext.of(plaintext), signature); __**(3)** ``` -------------------------------- ### Configure Cubbyhole Authentication with Wrapped Token Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Configures Cubbyhole authentication using a wrapped token. Override clientAuthentication() in a class extending AbstractVaultConfiguration, using CubbyholeAuthenticationOptions with initialToken and wrapped() builder methods, then create CubbyholeAuthentication with restOperations(). ```java @Configuration class AppConfig extends AbstractVaultConfiguration { // … @Override public ClientAuthentication clientAuthentication() { CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions .builder() .initialToken(VaultToken.of("…")) .wrapped() .build(); return new CubbyholeAuthentication(options, restOperations()); } // … } ``` -------------------------------- ### PEM-encoded certificate SSL configuration Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Shows how to configure SSL using PEM-encoded certificates instead of a Java Key Store. The PEM file may contain one or more certificates; certificates are added to the underlying KeyStore using the full subject name as alias. ```java KeyStoreConfiguration keystore = KeyStoreConfiguration .of(new ClassPathResource("ca.pem")).withStoreType("PEM"); SslConfiguration configuration = SslConfiguration.forTrustStore(keystore); ``` -------------------------------- ### vault.properties file with Vault URI and token Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Defines the Vault URI and token used by EnvironmentVaultConfiguration. The token is a placeholder and should be replaced with a real token. ```properties vault.uri=https://localhost:8200 vault.token=00000000-0000-0000-0000-000000000000 ``` -------------------------------- ### Paging and Sorting Repository (findTop10ByIdStartsWithOrderBySocialSecurityNumberDesc) Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Defines a repository interface extending PagingAndSortingRepository with query methods that support paging and sorting. Sorting is applied after fetching all IDs, and paging uses offset/limit. ```java public interface CredentialsRepository extends PagingAndSortingRepository { List findTop10ByIdStartsWithOrderBySocialSecurityNumberDesc(String prefix); List findByIdStarts(String prefix, Pageable pageRequest); } ``` -------------------------------- ### JavaConfig for Vault Repositories Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Spring configuration enabling Vault repositories with @EnableVaultRepositories and providing a VaultTemplate bean. ```java @Configuration @EnableVaultRepositories public class ApplicationConfig { @Bean public VaultTemplate vaultTemplate() { return new VaultTemplate(…); } } ``` -------------------------------- ### Declare @VaultPropertySource path using placeholders Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Uses a placeholder in the Vault path that is resolved against existing property sources, with a fallback value. Throws IllegalArgumentException if unresolved and no default is given. ```java @Configuration @VaultPropertySource(value = "aws/creds/${my.placeholder:fallback/value}", propertyNamePrefix = "aws.", renewal = Renewal.ROTATE) public class AppConfig { } ``` -------------------------------- ### Token Authentication Backend - Token Operations Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Shows how to create, renew, and revoke Vault tokens using Spring Vault's VaultTokenOperations. ```APIDOC ## Token Authentication Backend ### Description This backend provides access token management, including creating, renewing, and revoking tokens. It is built-in and automatically available at `/auth/token`. ### Operations - **create()** - Creates a token by applying role defaults. - **create(VaultTokenRequest)** - Creates a token with fine-grained settings using the builder API. - **renew(VaultToken)** - Renews a token. - **revoke(VaultToken)** - Revokes a token. ### Example ```java VaultOperations operations = new VaultTemplate(new VaultEndpoint()); VaultTokenOperations tokenOperations = operations.opsForToken(); VaultTokenResponse tokenResponse = tokenOperations.create(); VaultToken justAToken = tokenResponse.getToken(); VaultTokenRequest tokenRequest = VaultTokenRequest.builder() .withPolicy("policy-for-myapp") .displayName("Access tokens for myapp") .renewable() .ttl(Duration.ofHours(1)) .build(); VaultTokenResponse appTokenResponse = tokenOperations.create(tokenRequest); VaultToken appToken = appTokenResponse.getToken(); tokenOperations.renew(appToken); tokenOperations.revoke(appToken); ``` ### Parameters - **VaultTokenRequest** (object) - Optional - Builder for token creation settings, including policy, display name, renewable flag, and TTL. ### Return Values - **VaultTokenResponse** - Contains the created token. - **VaultToken** - Value object representing a Vault token. ``` -------------------------------- ### Register VaultPropertySource programmatically Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Adds a VaultPropertySource with highest precedence to the environment's property sources. Properties stored in Vault are then detected ahead of other sources. ```java ConfigurableApplicationContext ctx = new GenericApplicationContext(); MutablePropertySources sources = ctx.getEnvironment().getPropertySources(); sources.addFirst(new VaultPropertySource(vaultTemplate, "secret/my-application")); ``` -------------------------------- ### Write and read secret using VaultTemplate Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Shows how to use VaultTemplate directly to write and read a secret at 'secret/elvis'. The kv secrets engine is mounted at 'secret'. The write operation stores a 'social-security-number' key, and the read operation retrieves it. ```java VaultOperations operations = new VaultTemplate(new VaultEndpoint()); operations.write("secret/elvis", Collections.singletonMap("social-security-number", "409-52-2002")); VaultResponse read = operations.read("secret/elvis"); read.getRequiredData().get("social-security-number"); ``` -------------------------------- ### Configure Cubbyhole Authentication with Stored Token Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Configures Cubbyhole authentication using a stored token. Override clientAuthentication() in a class extending AbstractVaultConfiguration, using CubbyholeAuthenticationOptions with initialToken and path("cubbyhole/token") builder methods, then create CubbyholeAuthentication with restOperations(). ```java @Configuration class AppConfig extends AbstractVaultConfiguration { // … @Override public ClientAuthentication clientAuthentication() { CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions .builder() .initialToken(VaultToken.of("…")) .path("cubbyhole/token") .build(); return new CubbyholeAuthentication(options, restOperations()); } // … } ``` -------------------------------- ### doWithVault Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Composes a reactive sequence with the given WebClient, allowing interaction with Vault without a session context. This is useful for operations that do not require authentication, such as initializing Vault. ```APIDOC ## doWithVault ### Description Composes a reactive sequence with the given WebClient, allowing interaction with Vault without a session context. ### Method Function clientCallback ### Parameters - **clientCallback** (Function) - Required - A function that takes a WebClient and returns a reactive sequence result. ### Example ```java reactiveVaultOperations.doWithVault(webClient -> { return webClient.put() .uri("/sys/init") .syncBody(request) .retrieve() .toEntity(VaultInitializationResponse.class); }); ``` ``` -------------------------------- ### Configure Azure (MSI) authentication with AzureMsiAuthentication Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Enables Azure managed service identity authentication. VM environment details (subscription Id, resource group, VM name) can be configured via AzureMsiAuthenticationOptionsBuilder; if left unconfigured, AzureMsiAuthentication queries Azure's instance metadata service. ```java @Configuration class AppConfig extends AbstractVaultConfiguration { // … @Override public ClientAuthentication clientAuthentication() { AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder() .role(…).build(); return new AzureMsiAuthentication(options, restOperations()); } // … } ``` -------------------------------- ### Configure AWS-IAM authentication with instance profile credentials Source: https://docs.spring.io/spring-vault/docs/2.3.x/reference/html Uses AwsIamAuthentication with an InstanceProfileCredentialsProvider as the credentials source. This is suitable for AWS-EC2, Lambda, and ECS environments with assigned IAM principals. ```java @Configuration class AppConfig extends AbstractVaultConfiguration { // … @Override public ClientAuthentication clientAuthentication() { AwsIamAuthenticationOptions options = AwsIamAuthenticationOptions.builder() .credentialsProvider(InstanceProfileCredentialsProvider.getInstance()).build(); return new AwsIamAuthentication(options, restOperations()); } // … } ```