In this post, lets have a look at how easy it is to configure Managed Service Identity for an Azure Function and how it can be used together with Key Vault to secure sensitive information like Client Ids, Client Secrets and Passwords.
For example, when building an Azure Function which will interact with some data in SharePoint Online, we need a way to authenticate the Function with SharePoint. Two common methods used for authentication are 1) By creating an Add-In registration in SharePoint (appregnew.aspx) and 2) By using Azure AD authentication by creating an App Registration in Azure AD.
In both cases, we need to secure the ClientID and ClientSecret for the registration in such a way that only our calling code has access and any non-admin user browsing the Azure Function in the portal is prevented from seeing the sensitive data. So let's see how we can do that using Managed Service Identity:
1) They very first thing you need to do is make sure that Managed Service Identity is configured for your Function App. You can do this simply by going to Function App Settings -> Managed Service Identity and ensuring that it is turned ON.
2) Create a Key Vault (or go to an existing one) and create two Secrets with names "ClientID" and "ClientSecret". You can also create additional Secrets relevant to your solution here.
3) Now we want our Azure Function App to have permissions to access the Key Vault. To do this, go to Access Policies -> Add New
4) Select the Function App as the principal and make sure under Secret permissions, it has at least the "Get" permission:
5) That's it in terms of the config! Now let's move on to the code to access the secured Client ID and Secret:
Make sure your Azure Function has the following NuGet packages:
Microsoft.Azure.KeyVault
Microsoft.Azure.Services.AppAuthentication
And here is an HTTP triggered .NET pre-compiled function which fetches the ClientId and ClientSecret from the Key Vault:
Quick note on pricing for MSI and Key Vault:
MSI is totally free to use and comes with the free version Azure Active Directory. The cost for storing secrets in the Key Vault is charged by number of access operations but it is pretty cheap as well. You could even go a step further and use caching in your code to reduce the number of access operations.
Update (5th August 2018): You can also use MSI when debugging locally. The steps to achieve that are added in this tweet:
This also works with local debugging in Visual Studio. Just make sure— Vardhaman Deshpande (@vrdmn) July 31, 2018
1)The current user has permissions though the Key Vault access policy
2)Using Azure CLI 2.0, sign in with the same user by doing az login
3)F5 debug, enjoy!
Thanks to @__shreyas for the tip! https://t.co/KtLrygwZq8
No comments:
Post a Comment