# How to access secrets in Azure Key Vault using Java

## What is Azure Key Vault?

[Azure Key Vault](https://azure.microsoft.com/en-us/services/key-vault/) is a cloud service offered by Microsoft to securely store cryptographic keys, certificates, and secrets. At StratoGator we use Key Vault as part of our solution to keep our client secrets secure.

## How do I get started

The following information is required to access the Key Vault:

- Key Vault URL
- Client Id
- Client Key (or certificate)

### Key Vault URL

Create the Key Vault through the Azure Portal. The name you choose for the key vault will determine the first part of the URL:

https://_your_key_vault_name_.vault.azure.net

### Client Id

To locate your client/application id:

1. Navigate to Azure Active Directory.
2. Select “App Registrations”.
3. Choose your application.
4. The Application ID can be copied from the page that appears.

### Client Key

To generate a client/application key:

1. Navigate to Azure Active Directory.
2. Select “App Registrations”.
3. Choose your application.
4. Select the “Keys” blade.
5. Add a new key and hit “Save”.
6. When you create your new key, the secret value will be revealed. This is your only opportunity to copy the key value.

### Permissions

In order for your application to have access to the Key Vault contents, you must set the appropriate permissions for your application in the Key Vault.

1. Navigate to Key vaults.
2. Select your Key Vault.
3. Select the “Access Policies” blade.
4. Select “Add new”.
5. Choose your application as the Principal.
6. Select the minimum required permissions for your application.
7. Hit “OK” to complete.
8. Select “Save” to save your new access policy.

## Dependencies

Accessing an Azure Key Vault using Java requires the [Azure SDK for Java](https://github.com/Azure/azure-sdk-for-java/) ([Maven link](https://mvnrepository.com/artifact/com.microsoft.azure/azure)) and [Azure KeyVault SDK for Java](https://github.com/Azure/azure-sdk-for-java/tree/master/azure-mgmt-keyvault) ([Maven link](https://mvnrepository.com/artifact/com.microsoft.azure/azure-keyvault)).

These dependencies must be added to your pom.xml:

|        |                                                             |
|--------|-------------------------------------------------------------|
| 1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10 | <dependency><br><groupId>com.microsoft.azure</groupId><br><artifactId>azure</artifactId><br><version>1.3.0</version><br></dependency><br><dependency><br><groupId>com.microsoft.azure</groupId><br><artifactId>azure-keyvault</artifactId><br><version>1.0.0</version><br></dependency> |

## Connection

You must implement a _KeyVaultCredentials_ class to connect to the Key Vault. The follow is an example adapted from the [Microsoft KeyVaultCredentials API documentation](https://azure.github.io/azure-sdk-for-java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.html#doAuthenticate-java.lang.String-java.lang.String-java.lang.String-).

|        |                                                             |
|--------|-------------------------------------------------------------|
| 1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>13<br>14<br>15<br>16<br>17<br>18<br>19<br>20<br>21<br>22<br>23<br>24<br>25<br>26<br>27<br>28<br>29<br>30<br>31<br>32<br>33<br>34<br>35<br>36<br>37<br>38<br>39<br>40<br>41<br>42<br>43<br>44<br>45<br>46<br>47<br>48<br>49<br>50<br>51<br>52<br>53<br>54<br>55<br>56 | package com.example.azure.keyvault;<br>import com.microsoft.aad.adal4j.AuthenticationContext;<br>import com.microsoft.aad.adal4j.AuthenticationResult;<br>import com.microsoft.aad.adal4j.ClientCredential;<br>import com.microsoft.azure.keyvault.authentication.KeyVaultCredentials;<br>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br>import java.util.concurrent.Future;<br>/\*<br>\* Based on example from Microsoft documentation:<br>\* https://azure.github.io/azure-sdk-for-java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.html<br>\*/<br>public class ClientSecretKeyVaultCredential extends KeyVaultCredentials<br>{<br>private String clientId;<br>private String clientKey;<br>public ClientSecretKeyVaultCredential(String clientId, String clientKey ){<br>this.clientId= clientId;<br>this.clientKey= clientKey;<br>}<br>    @Override<br>public String doAuthenticate(String authorization, String resource, String scope){<br>        AuthenticationResult token = getAccessTokenFromClientCredentials(<br>                authorization, resource, clientId, clientKey);<br>return token.getAccessToken();<br>}<br>private static AuthenticationResult getAccessTokenFromClientCredentials(<br>String authorization, String resource, String clientId, String clientKey){<br>        AuthenticationContext context = null;<br>        AuthenticationResult result = null;<br>        ExecutorService service = null;<br>try{<br>            service = Executors.newFixedThreadPool(1);<br>            context = new AuthenticationContext(authorization, false, service);<br>            ClientCredential credentials = new ClientCredential(clientId, clientKey);<br>            Future<AuthenticationResult> future = context.acquireToken(<br>                    resource, credentials, null);<br>            result = future.get();<br>} catch(Exception e){<br>throw new RuntimeException(e);<br>} finally{<br>            service.shutdown();<br>}<br>if(result == null){<br>throw new RuntimeException("authentication result was null");<br>}<br>return result;<br>}<br>} |

## Access Key Vault information

Use the _KeyVaultCredentials_ class you’ve created to instantiate a _KeyVaultClient_, and then perform your actions.

[KeyVaultClient API documentation](https://docs.microsoft.com/en-us/java/api/com.microsoft.azure.keyvault._key_vault_client)

For example:

|        |                                                             |
|--------|-------------------------------------------------------------|
| 1<br>2<br>3<br>4<br>5<br>6<br>7<br>8 | // ClientSecretKeyVaultCredential is the implementation of KeyVaultCredentials<br>KeyVaultClient client = new KeyVaultClient(<br>new ClientSecretKeyVaultCredential(clientId, clientKey));<br>// KEYVAULT_URL is the location of the keyvault to use: https://yourkeyvault.vault.azure.net<br>// "testSecret" is the name of the secret in the key vault<br>SecretBundle secret = client.getSecret( KEYVAULT_URL, "testSecret");<br>log(secret.value()); |

## Related Links

[How to use keys, secrets and certificates with Key Vault](https://docs.microsoft.com/en-us/rest/api/keyvault/about-keys--secrets-and-certificates)

[Spring Boot Starter](https://github.com/Microsoft/azure-spring-boot/tree/master/azure-spring-boot-starters/azure-keyvault-secrets-spring-boot-starter)
