Integrate Azure Key Vault With Python Flask


Here’s a complete end-to-end guide on how to integrate Azure Key Vault with a Python Flask application, including all the necessary steps for both local and production environments.

Prerequisites:

  1. Azure Subscription: You need an active Azure subscription. If you don’t have one, create a free account at Azure Free Account.

  2. Azure Key Vault: Set up an Azure Key Vault instance in your Azure portal. Here’s how:

    • Go to the Azure portal.
    • Search for Key Vault and create a new Key Vault.
    • After the Key Vault is created, go to the Secrets section and add a new secret (e.g., MySecret with a value).
  3. Azure Active Directory (AAD): Make sure your Flask app is registered with Azure AD (if you’re using Service Principal or Managed Identity for authentication).

  4. Install Azure CLI: If you’re developing locally, ensure that Azure CLI is installed and you’re signed in (az login).

Step 1: Install Required Libraries

Install the required libraries using pip:

pip install azure-identity azure-keyvault-secrets flask
  • azure-identity: Allows authentication to Azure services.
  • azure-keyvault-secrets: Interacts with Azure Key Vault secrets.
  • flask: Web framework to build the app.

Step 2: Set Up Azure Authentication

You can authenticate your application in different ways. Below, I’ll cover two approaches:

  1. Using Azure CLI for local development (DefaultAzureCredential).
  2. Using Service Principal for production or automated environments.

Option 1: Azure CLI Authentication (Local Development)

  1. Open your terminal and log in with the Azure CLI:

    az login
  2. The DefaultAzureCredential will use the credentials from the CLI for authentication.

Option 2: Using Service Principal (Production)

  1. First, create a Service Principal in the Azure Portal (or via CLI).

  2. Set up environment variables with the Service Principal credentials:

    export AZURE_CLIENT_ID="<your-client-id>"
    export AZURE_TENANT_ID="<your-tenant-id>"
    export AZURE_CLIENT_SECRET="<your-client-secret>"

For production, using Managed Identity (if deployed on Azure) is recommended for secure and seamless authentication.

Step 3: Create the Flask Application

Create a new Python file, e.g., app.py, and set up the Flask application to integrate with Azure Key Vault.

from flask import Flask
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient

app = Flask(__name__)

# Azure Key Vault URL (replace with your actual Key Vault URL)
KEY_VAULT_URL = "https://<your-keyvault-name>.vault.azure.net/"

# Set up DefaultAzureCredential (uses environment variables, Azure CLI, Managed Identity, etc.)
credential = DefaultAzureCredential()

# Create a client to interact with Azure Key Vault secrets
secret_client = SecretClient(vault_url=KEY_VAULT_URL, credential=credential)

@app.route('/')
def get_secret():
    try:
        # Replace '<your-secret-name>' with the actual name of your secret in Azure Key Vault
        secret_name = "<your-secret-name>"
        secret = secret_client.get_secret(secret_name)
        return f"Secret Value: {secret.value}"
    except Exception as e:
        return f"Error: {str(e)}"

if __name__ == "__main__":
    app.run(debug=True)

Explanation of Code:

  1. DefaultAzureCredential: This is the Azure SDK's recommended way to authenticate. It will automatically try different authentication methods, including Azure CLI, environment variables, and Managed Identity (if running on Azure).

  2. SecretClient: This client is used to interact with the Key Vault and retrieve secrets.

  3. get_secret: The route / retrieves the secret value from the Key Vault using the secret name provided in the application.

Step 4: Configure Key Vault Permissions

Make sure the application (via Service Principal or Managed Identity) has permission to access secrets in Azure Key Vault:

  1. Go to the Azure Key Vault in the portal.
  2. Under Access policies, add a new policy.
  3. Select the appropriate Principal (your Service Principal or Managed Identity).
  4. Grant Get permission for secrets.

Step 5: Running the Flask Application

  1. Ensure your environment is set up with the necessary credentials, either via Azure CLI or environment variables for Service Principal.

  2. Run the Flask app:

    python app.py
  3. The Flask app will start running at http://127.0.0.1:5000/. If the app is correctly authenticated, it will display the secret value from Azure Key Vault at this URL.

Step 6: Deploying to Production (Optional)

When deploying the Flask application to production, it’s best to use Managed Identity for authentication. This way, your app does not require hardcoded credentials (such as client ID or client secret). Managed Identity is supported when deploying to Azure services like Azure App Service, Azure Functions, or Azure Virtual Machines.

  1. Enable Managed Identity for your Azure service.
  2. Assign the Managed Identity the necessary access to your Key Vault.
  3. Modify your code to authenticate using Managed Identity, which is automatically handled by DefaultAzureCredential.
credential = DefaultAzureCredential()  # It will pick up Managed Identity automatically

You now have a fully integrated Azure Key Vault with a Python Flask application, capable of securely retrieving secrets from the Key Vault. This setup can be easily extended for other Azure services or more complex secret management scenarios.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete