Connecting Azure Functions to Key Vault

Azure Functions is really nice when you want to run some code, and this post shows how to connect your Function to Key Vault so that you don’t have to store secrets in your Azure Function. In this example I’ll be using PowerShell and with that runtime version 1 of Azure Functions.

Step 1 is to activate managed service identity in platform settings and identity in your Azure Function

Next, you can go into your Key Vault and add an access policy for your app. I add it with two secret permissions; Get and List. Here you can also see that I have a similar access policy for my Data Factory.

Key Vault access policy for the app

Next step is to add the secrets to your app settings. This can be done like this:

Next you want to get the actual secrets, and that is done with @Microsoft.KeyVault(SecretUri=<secret uri with version>. The URI for the secret can be copied from KeyVault

Adding secrets to app settings

Then you can just use these settings (and this is basically everything you need in the function app)

#receive token from Strava
$authUrl = "https://www.strava.com/oauth/token"
$body = @{
"client_id"=$env:APPSETTING_StravaClientId;
"client_secret"=$env:APPSETTING_StravaClientSecret;
"grant_type"="refresh_token";
"refresh_token"=$env:APPSETTING_StravaRefreshToken
}
$authResponse = Invoke-RestMethod -Uri $authUrl –Method POST -Body $body

$token = $authResponse.access_token
#Out-File -Encoding Ascii -FilePath $res -inputObject "Hello $token"
$out = $authResponse | ConvertTo-Json

#$restResponse | Out-File -FilePath $res
$out | Out-File $res -Encoding Ascii

That’s it! For security I have required Azure AD authentication to run this function, and how to set that up in Data Factory can be read in this post.

My first version of this post claimed that the app setting method requires runtime 2, but this was pointed out to me by Sirar Salih, so I’ve updated the post to reflect this simpler approach. Thanks for the help Sirar!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.