How to use the Spring Boot Starter for Azure Key Vault

This article demonstrates creating an app with the Spring Initializr that uses the Spring Boot Starter for Azure Key Vault to retrieve a connection string that is stored as a secret in a key vault.

Prerequisites

The following prerequisites are required in order to complete the steps in this article:

Create an app using Spring Initializr

The following procedure creates the application using Spring Initializr.

  1. Browse to https://start.spring.io/.

  2. Specify that you want to generate a Maven project with Java.

  3. Enter the Group and Artifact names for your application.

  4. In the Dependencies section, enter Azure Key Vault.

  5. Scroll to the bottom of the page and click Generate.

    Generate Spring Boot project

  6. When prompted, download the project to a path on your local computer.

Sign into Azure

The following procedure authenticates the user in Azure CLI.

  1. Open a command prompt.

  2. Sign into your Azure account by using the Azure CLI:

    az login
    

Follow the instructions to complete the sign-in process.

  1. List your subscriptions:

    az account list
    

    Azure will return a list of your subscriptions, and you will need to copy the GUID for the subscription that you want to use; for example:

    [
      {
        "cloudName": "AzureCloud",
        "id": "ssssssss-ssss-ssss-ssss-ssssssssssss",
        "isDefault": true,
        "name": "Converted Windows Azure MSDN - Visual Studio Ultimate",
        "state": "Enabled",
        "tenantId": "tttttttt-tttt-tttt-tttt-tttttttttttt",
        "user": {
          "name": "contoso@microsoft.com",
          "type": "user"
        }
      }
    ]
    
  2. Specify the GUID for the account you want to use with Azure; for example:

    az account set -s ssssssss-ssss-ssss-ssss-ssssssssssss
    

Create a new Azure Key Vault

The following procedure creates and initializes the key vault.

  1. Create a resource group for the Azure resources you will use for your key vault; for example:

    az group create --name vged-rg2 --location westus
    

    Where:

    Parameter Description
    name Specifies a unique name for your resource group.
    location Specifies the Azure region where your resource group will be hosted.

    The Azure CLI will display the results of your resource group creation; for example:

    {
      "id": "/subscriptions/ssssssss-ssss-ssss-ssss-ssssssssssss/resourceGroups/vged-rg2",
      "location": "westus",
      "managedBy": null,
      "name": "vged-rg2",
      "properties": {
        "provisioningState": "Succeeded"
      },
      "tags": null
    }
    
  2. Create an Azure service principal from your application registration; for example:

    az ad sp create-for-rbac --name "vgeduser"
    

    Where:

    Parameter Description
    name Specifies the name for your Azure service principal.

    The Azure CLI will return a JSON status message that contains the appId and password, which you will use later as the client ID and client password; for example:

    {
      "appId": "iiiiiiii-iiii-iiii-iiii-iiiiiiiiiiii",
      "displayName": "vgeduser",
      "name": "http://vgeduser",
      "password": "pppppppp-pppp-pppp-pppp-pppppppppppp",
      "tenant": "tttttttt-tttt-tttt-tttt-tttttttttttt"
    }
    
  3. Create a new key vault in the resource group; for example:

    az keyvault create --name vgedkeyvault --resource-group vged-rg2 --location westus --enabled-for-deployment true --enabled-for-disk-encryption true --enabled-for-template-deployment true --sku standard --query properties.vaultUri
    

    Where:

    Parameter Description
    name Specifies a unique name for your key vault.
    location Specifies the Azure region where your resource group will be hosted.
    enabled-for-deployment Specifies the key vault deployment option.
    enabled-for-disk-encryption Specifies the key vault encryption option.
    enabled-for-template-deployment Specifies the key vault encryption option.
    sku Specifies the key vault SKU option.
    query Specifies a value to retrieve from the response, which is the key vault URI that you will need to complete this tutorial.

    The Azure CLI will display the URI for key vault, which you will use later; for example:

    "https://vgedkeyvault.vault.azure.net"
    
    
  4. Set the access policy for the Azure service principal you created earlier; for example:

    az keyvault set-policy --name vgedkeyvault --secret-permission set get list delete --spn "iiiiiiii-iiii-iiii-iiii-iiiiiiiiiiii"
    

    Where:

    Parameter Description
    name Specifies your key vault name from earlier.
    secret-permission Specifies the security policies for your key vault.
    spn Specifies the GUID for your application registration from earlier.

    The Azure CLI will display the results of your security policy creation; for example:

    {
      "id": "/subscriptions/ssssssss-ssss-ssss-ssss-ssssssssssss/...",
      "location": "westus",
      "name": "vgedkeyvault",
      "properties": {
        ...
        ... (A long list of values will be displayed here.)
        ...
      },
      "resourceGroup": "vged-rg2",
      "tags": {},
      "type": "Microsoft.KeyVault/vaults"
    }
    
  5. Store a secret in your new key vault; for example:

    az keyvault secret set --vault-name "vgedkeyvault" --name "connectionString" --value "jdbc:sqlserver://SERVER.database.windows.net:1433;database=DATABASE;"
    

    Where:

    Parameter Description
    vault-name Specifies your key vault name from earlier.
    name Specifies the name of your secret.
    value Specifies the value of your secret.

    The Azure CLI will display the results of your secret creation; for example:

    {
      "attributes": {
        "created": "2017-12-01T09:00:16+00:00",
        "enabled": true,
        "expires": null,
        "notBefore": null,
        "recoveryLevel": "Purgeable",
        "updated": "2017-12-01T09:00:16+00:00"
      },
      "contentType": null,
      "id": "https://vgedkeyvault.vault.azure.net/secrets/connectionString/123456789abcdef123456789abcdef",
      "kid": null,
      "managed": null,
      "tags": {
        "file-encoding": "utf-8"
      },
      "value": "jdbc:sqlserver://.database.windows.net:1433;database=DATABASE;"
    }
    

Configure and compile your app

Use the following procedure to configure and compile your application.

  1. Extract the files from the Spring Boot project archive files that you downloaded earlier into a directory.

  2. Navigate to the src/main/resources folder in your project and open the application.properties file in a text editor.

  3. Add the values for your key vault using values from the steps that you completed earlier in this tutorial; for example:

    azure.keyvault.uri=https://vgedkeyvault.vault.azure.net/
    azure.keyvault.client-id=iiiiiiii-iiii-iiii-iiii-iiiiiiiiiiii
    azure.keyvault.client-key=pppppppp-pppp-pppp-pppp-pppppppppppp
    

    Where:

    Parameter Description
    azure.keyvault.uri Specifies the URI from when you created your key vault.
    azure.keyvault.client-id Specifies the appId GUID from when you created your service principal.
    azure.keyvault.client-key Specifies the password GUID from when you created your service principal.
  4. Navigate to the main source code file of your project; for example: /src/main/java/com/vged/secrets.

  5. Open the application's main Java file in a file in a text editor; for example: SecretsApplication.java, and add the following lines to the file:

    package com.vged.secrets;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.CommandLineRunner;
    
    @SpringBootApplication
    public class SecretsApplication implements CommandLineRunner {
    
       @Value("${connectionString}")
       private String connectionString;
    
       public static void main(String[] args) {
          SpringApplication.run(SecretsApplication.class, args);
       }
    
       public void run(String... varl) throws Exception {
          System.out.println(String.format("\nConnection String stored in Azure Key Vault:\n%s\n",connectionString));
       }
    }
    

    This code example retrieves the connection string from the key vault and displays it to the command line.

  6. Save and close the Java file.

Build and test your app

Use the following procedure to test your application.

  1. Navigate to the directory where the pom.xml file for your Spring Boot app is located:

  2. Build your Spring Boot application with Maven; for example:

    mvn clean package
    

    Maven will display the results of your build.

    Spring Boot application build status

  3. Run your Spring Boot application with Maven; the application will display the connection string from your key vault. For example:

    mvn spring-boot:run
    

    Spring Boot run time message

Summary

In this tutorial, you created a new Java web application using the Spring Initializr, created an Azure Key Vault to store sensitive information, and then configured your application to retrieve information from your key vault.

Next steps

To learn more about Spring and Azure, continue to the Spring on Azure documentation center.

Additional Resources

For more information about using Azure Key Vaults, see the following articles:

For more information about using Spring Boot applications on Azure, see the following articles:

For more information about using Azure with Java, see the Azure for Java Developers and the Working with Azure DevOps and Java.