Search Tutorials


Spring Boot + Azure Managed Identity Example | JavaInUse

Spring Boot + Azure Managed Identity Example

Managed Identity in Azure is a feature that provides Azure services with an automatically managed identity in Azure Active Directory (Azure AD). This identity can be used to authenticate to other Azure services without needing to manage credentials. Essentially, it allows your applications to securely access Azure resources without storing or managing secrets like passwords or certificates.

Why Should You Use Managed Identity?

  • Enhanced Security: By eliminating the need to manage and store credentials, you reduce the risk of credential exposure and misuse.
  • Simplified Management: Managed Identities automatically handle the lifecycle of credentials, including rotation, which simplifies the administrative overhead.
  • Seamless Integration: It integrates seamlessly with Azure services, making it easier to implement secure authentication and authorization across your Azure resources.
  • Cost-Effective: Since you don't need to manage and secure credentials manually, it can save time and resources, leading to cost savings.
  • Compliance: Using Managed Identities can help meet compliance requirements by ensuring that access to resources is controlled and audited through Azure AD.
  • In summary, Managed Identity in Azure offers a secure, efficient, and simplified way to manage authentication and authorization for your applications and services.
We will be creating a spring boot application which will fetch secrets from azure key vault. This spring boot application will be deployed on an azure vm to which we will be assigning a managed identity which has the azure key vault access. As we are using managed identity so the spring boot application will not need to pass any credentials to get the secrets from azure key vault.
Spring Boot Azure Key Vault

Create Azure Key Vault

Create azure key vault named javainuse-keyvault
Spring Boot Create Azure Key Vault
The key vault is created as follows -
Spring Boot List Azure Key Vault

Admin Access to Azure Key Vault

Next we give keyvault administrator access to the azure portal user.
Spring Boot List Azure Key Vault

Spring Boot List Azure Key Vault
This allows us to create a secret named new-secret -
Spring Boot Azure Key Vault Secret

Create Managed Identity

Next we create a managed identity named javainuse-identity
Spring Boot Azure Managed Identity
The managed identity is created as follows-
Spring Boot Azure Managed Identity

Give Managed Identity - Access To Key Vault

For the created managed identity we give key vault reader and key vault secrets access to the azure key vault.
Spring Boot Azure Managed Identity Read

Spring Boot Azure Managed Identity Read

Spring Boot Azure Managed Identity Key Vaults Secrets

Spring Boot Azure Managed Identity Key Vaults Secrets

Allocate Azure VM

Create an azure vm of type windows. Also configure the username and password to access this vm.
Spring Boot Azure Virtual Machine

Spring Boot Azure VM
The VM is created as follows-
Spring Boot Azure VM

Spring Boot + Azure Key Vault Application

Next using RDP we will be accessing this VM.
Spring Boot Azure VM
In this VM we will be configuring java and installing eclipse.
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 ManagedIdentityCredentialBuilder, to which we have passed the client id of the managed identity.
  • 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.core.credential.TokenCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;
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-keyvault.vault.azure.net/";
		String secretName = "new-secret";
		String fetchedSecret = null;

		try {
			
			TokenCredential tokenCredential = new ManagedIdentityCredentialBuilder().clientId("d266f307-b9ff-4483-b62d-a8c178ffa5f6").build();
			// Create a SecretClient instance to interact with Azure Key Vault
			SecretClient secretClient = new SecretClientBuilder().vaultUrl(keyVaultUrl)
					.credential(tokenCredential).buildClient();

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

			System.out.println("Truststore created successfully at: " + fetchedSecret);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fetchedSecret;
	}

}

Assign Managed Identity to Azure VM

Before running the spring boot application we will be assigning managed identity to azure vm. Now run the spring boot application. If we now go to localhost:8080/getsecret

Download Source Code

Download it -
Spring Boot 3 + Azure Managed Identity Example