Edit

Share via


Apps, API Keys, and Azure Key Vault secrets

Azure Key Vault is an Azure service that safeguards cryptographic keys, secrets, and certificates. It provides a centralized, secure, and highly available repository for sensitive information like API keys. One method of avoiding the insecure practice of embedding API keys directly in your application's source code is to configure your app to securely interact with API keys that are stored in Azure Key Vault.

In this article you learn how to create a Key Vault instance, add an API key as a secret to this key vault, and then configure the key vault using best practices. These best practices include restricting access using role based access control (RBAC), enabling monitoring, and restricting network access.

Creating and securing an Azure Key Vault instance

Azure Key Vault allows you to securely store cryptographic keys, secrets, and certificates. You should deploy separate key vaults for different environments (development, staging, production) and applications.

Create a Resource group and key vault instance

To create a key vault instance, you can use the following command from Azure CLI or Azure Cloud Shell:

  1. Use the az group create command to create a resource group:

    Azure CLI
    az group create --name myResourceGroup --location eastus
    

    You can change "eastus" to a location nearer to you, if you prefer.

  2. Use az keyvault create to create the key vault:

    Azure CLI
    az keyvault create --name <your-unique-keyvault-name> --resource-group myResourceGroup
    

    Replace <your-unique-keyvault-name> with a name that's unique across all of Azure. You typically use your personal or company name along with other numbers and identifiers.

Add an API key to Azure Key Vault as a secret

Once you have created the Azure Key Vault instance, you can add an API key as a secret to this Azure Key Vault instance.

The following uses the Azure CLI az keyvault secret set command to add a secret named MyApiKey to the keyvault and sets the secret to expire after 180 days:

Azure CLI
az keyvault secret set \
    --vault-name "<YourKeyVaultName>" \
    --name "MyApiKey" \
    --value "<YourSecretValue>"
    --expires "$(date -u -d '+180 days' +'%Y-%m-%dT%H:%M:%SZ')"

You should aim to rotate your API keys periodically. Depending on your organization's security needs, you may choose to rotate keys more or less frequently than every 180 days. You can configure an Event Grid subscription for the "SecretNearExpiry" event as a method of receiving notification about expiring API key secrets.

Restrict access to the Key Vault using RBAC

You can restrict access to the Azure Key Vault instance so that only the application's identity has access to Azure Key Vault.

To do this configure a Role Based Access Control (RBAC) role using the Azure CLI az role assignment create command:

Azure CLI
az role assignment create --role "Key Vault Secrets User" \
  --assignee <object-id-of-app-or-user> \
  --scope /subscriptions/<subscription-id>/resourcegroups/<resource-group-name>/providers/Microsoft.KeyVault/vaults/<key-vault-name>

Enable Key Vault logging and alerts

You should enable logging and alerts on your Key Vault instance as a method of detecting potentially suspicious activity.

To enable Azure Key Vault Logging and Alerts, use the Azure CLI az monitor diagnostic-settings create command:

Azure CLI
az monitor diagnostic-settings create \
    --name myDiagnosticSettings \
    --resource {key-vault-resource-id} \
    --logs '[{"category": "AuditEvent","enabled": true}]' \
    --workspace {log-analytics-workspace-id}

This command creates a diagnostic setting named myDiagnosticSettings, configures it for the specified Azure Key Vault, enables the AuditEvent log category, which tracks security and access-related events and sends the logs to the specified Log Analytics workspace for monitoring, analysis, and alerting. This allows you to monitor access patterns, detect unauthorized access attempts, and configure alerts for critical security events (for example, someone tries to access a secret without the right permissions).

You can run the Azure CLI az monitor scheduled-query create command to monitor logs in the specified Log Analytics workspace for unauthorized access attempts to Azure Key Vault secrets and trigger an alert if any matching unauthorized access attempt is detected:

Azure CLI
az monitor scheduled-query create \
    --name "Suspicious Access Alert" \
    --resource-group myResourceGroup \
    --scopes {log-analytics-workspace-resource-id} \
    --condition "AzureDiagnostics | where ResourceType == 'VAULTS' | where OperationName == 'SecretGet' | where ResultSignature == 'Unauthorized'"

Restrict network access to Key Vault

You should restrict network access to Azure Key Vault so that the vault only accepts requests from known network locations. There are two general methods you can use to do this:

  • Azure Private Link. This creates a private endpoint within your virtual network, allowing your application to connect to Azure Key Vault without traversing the public internet. This option is the most secure as traffic remains within your network, but requires creating a private endpoint and configuring DNS.
  • Firewall Rules. You can configure the Azure Key Vault firewall settings, located under Networks, with a list of allowed IP ranges. You can also use this method to allow access to existing virtual networks, but this requires that you enable a service endpoint for Microsoft.KeyVault on the selected subnet.

You can create a private endpoint using the Azure CLI az network private-endpoint create command:

Azure CLI
az network private-endpoint create \
    --name myPrivateEndpoint \
    --resource-group myResourceGroup \
    --vnet-name myVNet \
    --subnet mySubnet \
    --private-connection-resource-id /subscriptions/{subscription}/resourceGroups/{rg}/providers/Microsoft.KeyVault/vaults/{key-vault-name} \
    --group-id vault \
    --connection-name myConnection

You can create firewall rules on the Azure Key Vault instance using the Azure CLI [az keyvault network-rule add](/cli/azure/keyvault/network-rule#az-keyvault-network-rule-add) command, substituting the appropriate key vault names, resource groups, subnet, and subnet mask information:

```azurecli
az keyvault network-rule add \
    --name {key-vault-name} \
    --resource-group myResourceGroup \
    --ip-address {trusted-ip-address}/32

Azure Key Vault enforces HTTPS for all communications. This ensures that your API keys and other sensitive data are encrypted in transit, protecting them from eavesdropping and man-in-the-middle attacks.

Interact with Azure Key Vault using Python

To interact with Azure Key Vault using Python, install the Azure identity library for Microsoft Entra ID and the Azure Key Vault secrets library:

Python
pip install azure-identity
pip install azure-keyvault-secrets

You can use the Azure Identity and Azure Key Vault Secrets client library to manage secrets programmatically:

Python
from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential

key_vault_name = "<your-key-vault-name>"
KVUri = f"https://{key_vault_name}.vault.azure.net"
secret_name = "<your-secret-name>"

credential = DefaultAzureCredential()
client = SecretClient(vault_url=KVUri, credential=credential)

retrieved_secret = client.get_secret(secret_name)

# Now you can use the API key:

api_key = retrieved_secret.value
print(f"The API key is: {api_key}")

In this sample code:

  • DefaultAzureCredential: This class attempts to authenticate using various methods (environment variables, managed identities, etc.), making it suitable for different Azure environments.
  • SecretClient: This class provides methods to interact with secrets in Key Vault.
  • get_secret(): Retrieves the secret from Key Vault.

Next steps