DEV Community

loading...

Access Key Vault secret from Web Application

Shivappa
Software Developer
・4 min read

In the previous parts we have learnt how to create Azure Key Vault and how to add the principal in Azure Key Vault by whom it must be accessed.
In this part, we will learn how we can use secrets stored in Azure Key Vault in our Web Application.

Let's write a simple flask app to fetch the secrets from Key Vault.
Create a folder called KeyVaultDemo on your computer and open it in VS Code.
Create a new file requirements.txt which contains the packages required.
Add below contents to it.

flask
azure-keyvault-secrets
azure-identity

Enter fullscreen mode Exit fullscreen mode

azure-keyvault-secrets: It is a client library in python to access the secrets stored in Azure Key Vault. More information on this package can be found here.
azure-identity: It is an authentication library that provides different credential classes with which one can authenticate with the Active Directory.
To learn more on this package please check here.

We have added the packages required for our purpose.
Let's write actual code in which we can access the Key Vault secrets.
Create app.py file and dump the below contents to it.

import os

from flask import Flask

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

app = Flask(__name__)

# Save KEY VAULT URL in the web app application settings
AZUE_KEY_VAULT_URL = os.environ.get('AZUE_KEY_VAULT_URL', '')
# AZUE_KEY_VAULT_URL = "https://keyvaultdemoapp.vault.azure.net/"

@app.route('/secret')
def index():
    """Fetch secret from Azure Key Vault

    Returns:
        str: Response message to be displayed.
    """
    # Use Default credential. This has fallback authentication mechanism
    credential = DefaultAzureCredential()
    # Authenticate to Azure Key Vault.
    secret_client = SecretClient(vault_url=AZUE_KEY_VAULT_URL, credential=credential)
    # Fetch secrets created in Azure Key Vault
    secrets = secret_client.get_secret('firstsecret')
    name = secrets.name
    value = secrets.value
    # Show secret name and it's value in the response
    response = f'secret {name} value is {value}'
    return response

Enter fullscreen mode Exit fullscreen mode

Let's understand few lines from the above code snippet.

from azure.identity import DefaultAzureCredential

Azure identity helps to authenticate from the credentials we choose. Here we selected credential type as DefaultAzureCredential.
This is the most used credential type in most cloud applications because of the fallback mechanism supported.
First, it will try to check for Environment variables saved for the web application. If not then it will try to check in this order of authentication --> Managed Identity --> Visual Studio Code --> Azure Cli --> Interactive
Below Environment variables are required for Identity and must be added in Application settings in the web app deployed.

AZURE_CLIENT_ID --> This is the ID of an Azure Active Directory application
AZURE_CLIENT_SECRET --> This is the ID of application secrets created in Azure Active Directory.
AZURE_TENANT_ID --> This is the ID of the Active Directory Tenant.

To learn more on each method please look at the client library here.

Our code is ready and we will deploy it to Azure and access the application.
Right click on Explorer area in VS Code and click on Deploy to Web App...
VSCode-Deploy-1

  • Select your subscription.
  • Select Create new Web App..
  • Give a name to the web app. It should be Globally Unique name.
  • Select Runtime stack as Python 3.8
  • Select pricing tier as Free

It takes some time to deploy and you will see a successfully deployed message on the right bottom corner of VS Code.
Go to the Azure portal and go to the app created now and click on browse from the overview page.
It shows an error because we have not added the app environment in the app settings that we are accessing and using inside our flask app.

Let's add them to the Azure web app.
Go to Web App you just created.
Click on Configuration section under Settings.
Click on New application setting.
Add below Key value pair when prompted for entries.

Key : AZURE_CLIENT_ID
Value: Value which you copied when we created the authentication settings in the previous part

Repeat the above operation for the below Key addition.

  • AZURE_CLIENT_SECRET : corresponding value
  • AZURE_TENANT_ID : corresponding value
  • AZURE_KEY_VAULT_URL : This is the URL of the key vault created in this part. Go to Overview and on the right side you will see the keyvault URL.

Once you add all the entries, Save the settings.
The final application settings look like this web app configuration.
KeyVault-AppService-AppSettings-2

Now browse your application and see the secret name and secret value stored in Key Vault are displayed.
WebAppBrowse

We have learned how to use Azure Key Vault in your web application for storing the secrets securely.

To learn more on Azure Key Vault please refer to Microsoft documentation here.

That's all!
Thank you for reading my blog.
Stay tuned to read more blogs on Azure services.

Discussion (0)

Forem Open with the Forem app