Search Tutorials


Spring Boot + Azure Key Vault Hello World Example | JavaInUse

Spring Boot + Azure Key Vault Hello World Example

In the world of modern software development security is of paramount importance for any organization. Managing and securing sensitive information, such as API keys, database connection strings, and cryptographic keys is a critical concern.
  1. We can store these secrets directly in code or configuration files. However this poses a significant security risk. Any one who gets access to the code can get hold of these secrets.
  2. One solution to this might be to store the secret in an encrypted format. Microservices architecture is the most common architecture used for software development. In Microservices we might have hundreds or thousands of services that make use of some secret. Now suppose if we want to rotate the secret key. If this key is stored locally in some configuration file then it will need to be changed for all the microservices using it.
  3. Another approach where we store the configuration at some common file location like using the Spring Cloud Config Native Server or Spring Cloud Config Git Server. However we will then need to manage the whole authorization and authentication of various services trying to access these secrets.

Spring Boot 3 + Azure Key Vault Hello World Example
This is where Azure Key Vault comes into picture, offering a robust and secure solution for protecting and managing our application secrets. Azure Key Vault provides centralized management of the application secrets. Also it provides granular access control and auditing capabilities, allowing us to define precise permissions for who can access and manage our secrets.
In this tutorial we will be creating a spring boot application which will connect with Azure Key Vault and fetch secret from it.

Video

This tutorial is explained in the below Youtube Video.

Implementation

The implementation for our application will be as follows-
Spring Boot 3 + Azure Key Vault Example
First we will be create a keyvault, configure it and store a secret in it.

Create a key vault

Login to the azure keyvault.
Azure Portal Example
Search key vault and create a new one. Specify the following details
  • Resource Group
  • Key vault name
  • Region
  • Pricing Tier
Click create and create a new key vault.

Create secret

In the create keyvault named javainuse we will now create a secret named javainuse-secret and give it some value.
Azure Key Vault Java Example

Azure Key Vault Java Example
However when we try to create this secret, it gives an exception as below. This is because we do not have the permission to create the secret.
Azure Key Vault Java Example




Give role to user

In order to create a secret we will need to add the key vault administrator role to the user. We do this using the Access Control (IAM).
Azure Key Vault Access Control

Azure Key Vault Access Control key vault administrator

Azure Key Vault Access Control key vault administrator

Create secret

As before if we now try to create the secret we are able to do so successfully.
Azure Key Vault create secret

Create an enterprise application

Next in order to connect to the key vault using spring boot application we will need something called the client id and client secret. By default the key vault does not have it. We will need to create an enterprise application and then give the enterprise application some roles in the keyvault. Then using the enterprise applications client id and secret we will be able to connect to the key vault using spring boot application.
Go to Entra Id.
Azure Key Vault create secret
Go to Microsoft Entra Id -> App Registrations -> Create a new Registration Specify the name of the app as javainuseapp and click on Register button.
Azure Key Vault create secret
A new app named javainuseapp gets created. If we notice we get the client id and tenant id.
Azure Key Vault create secret
Let us now create a secret. For this go to Certificates & secrets and click on New client secret
Azure Key Vault create secret
A secret named clientsecret gets created.
Azure Key Vault create secret

Assign the javainuse app key vault role

For the key vault using the Access Control we will be assigning the Key Vault Secrets User role to the javainuseapp we just created.
Azure Key Vault create secret

Azure Key Vault create secret
We are done with the key vault configuration.

Spring Boot Application

Using the Spring Initializr we will be creating a spring boot application as follows.
Azure Key Vault create secret
The maven project created is as follows-
Azure Key Vault create secret
In the pom.xml we will be adding the azure dependencies. These dependencies provide the necessary libraries for integrating with Azure Key Vault in a Spring Boot application. Specifically, azure-security-keyvault-secrets allows you to securely retrieve secrets stored in Azure Key Vault, while azure-identity enables authentication and authorization mechanisms to access Key Vault securely using managed identities or service principals.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.2.6</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.javainuse</groupId>
	<artifactId>boot-keyvault</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>boot-keyvault</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>com.azure</groupId>
			<artifactId>azure-security-keyvault-secrets</artifactId>
			<version>4.8.3</version>
		</dependency>

		<dependency>
			<groupId>com.azure</groupId>
			<artifactId>azure-identity</artifactId>
			<version>1.9.1</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Next we will be creating a RestController named AzureController to use the Azure Key Vault client library in a Spring Boot application to securely retrieve secrets from Azure Key Vault and use them in your application.
In this class we expose a GET mapping for the "/getsecret" endpoint. When this endpoint is accessed, it performs the following actions:
  • It defines the Azure Key Vault URL and the name of the secret to be retrieved.
  • It creates an instance of the SecretClient from the Azure Key Vault client library using the SecretClientBuilder.
  • It authenticates with Azure Key Vault using the DefaultAzureCredentialBuilder, which automatically selects the appropriate credential type based on the environment.
  • It retrieves the secret value from Azure Key Vault using the getSecret method, passing the secret name.
  • The retrieved secret value is Base64-encoded, so it constructs a string with the message "Fetched Secret Values is " followed by the decoded secret value.
  • Finally, it returns the constructed string as the response to the "/getsecret" endpoint.
package com.javainuse.boot_keyvault.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.security.keyvault.secrets.SecretClient;
import com.azure.security.keyvault.secrets.SecretClientBuilder;
import com.azure.security.keyvault.secrets.models.KeyVaultSecret;

@RestController
public class AzureController {

	@GetMapping("/getsecret")
	public String hello() {
		String keyVaultUrl = "https://javainuse.vault.azure.net/";
		String secretName = "secret";
		String fetchedSecret = null;

		try {
			// Create a SecretClient instance to interact with Azure Key Vault
			SecretClient secretClient = new SecretClientBuilder().vaultUrl(keyVaultUrl)
					.credential(new DefaultAzureCredentialBuilder().build()).buildClient();

			// Retrieve the Base64-encoded secret from Azure Key Vault
			KeyVaultSecret secret = secretClient.getSecret(secretName);
			fetchedSecret = "Fetched Secret Values is " + secret.getValue();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return fetchedSecret;
	}

}
DefaultAzureCredentialBuilder selects the client id, client secret and tenant id from the environment variables. So we will need to set these as AZURE_CLIENT_ID,AZURE_CLIENT_SECRET and AZURE_TENANT_ID. DefaultAzureCredentialBuilder internally calls the azure entra id, with these environment variables calls and gets the access token. Then using the access token it can retrieve the secrets from keyvault. This all is done behind the scenes by DefaultAzureCredentialBuilder.
Azure Key Vault create secret
If we now start the application and go to localhost:8080/getsecret we see that the secret is retrieved correctly.
Azure Key Vault create secret

Download Source Code

Download it -
Spring Boot 3 + Azure Key Vault HelloWorld Example