In this article, let’s publish the web application as Azure app service. Then the app service will need managed identity to authenticate itself with the Azure key vault. So, we will create the system-assigned managed identity for Azure app service and will add access policy to allow it access on key vault.
Publish Web App
Make sure that the storage account details are not available in
Access the Web App
If you try to access the Azure app service you published just now using URL <a rel="noreferrer noopener" href="https://<https://<<app-service>>.azurewebsites.net , then you will get an error below:
This code tries to reach out to key vault and tries to get all the configurations from there. The key vault is not able to authenticate identity of the app service and the application crashes in startup resulting in above output.
Create Managed Identity
In order to authenticate the Azure web app with key vault, let’s use system-assigned managed identity.
Under system-assigned tab, toggle the Status field on as shown below. This should show a GUID and button below. Then click the Save button to save the newly generated identity.
So, we just have asked system to generate a managed identity for our app service.
Using Azure CLI
You can create system-assigned managed identity for the app service using below command:
|## Create system-assigned managed identity|
|az webapp identity assign –name azureappservicename –resource-group myResourceGroup|
|## Output of above command is as below.|
|## "principalId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",|
|## "tenantId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",|
|## "type": "SystemAssigned"|
|## principalId is required for setting access policy through CLI|
Key Vault Access Policy
Under Settings, select access policies option from left navigation and then click on Add access policy. On the new panel, make sure to select two permissions –
List – for
secret permissions and
certificate permissions inputs.
Then click on Select principal which should open a new panel on right side. On this new panel, search for the name of the app service which you have created for this demo. Select app service and then click on Select button.
Then click on Add button to add the access policy. This will close add policy panel. Then click on Save button on
Access policies panel.
Using Azure CLI
|## key vault name should be updated|
|## PrincipalId is from output of generate system-assigned identity for web app|
|az keyvault set-policy –name myKeyVault –object-id <PrincipalId> –secret-permissions get list|
Run and Verify
If the app service is accessed again, it should show the upload file page as shown below. If file is uploaded, application will be able to read the storage account name, blob container and key from key vault and so the file will be uploaded to blob container.
I hope this article have provided you some information on how to use system-assigned managed identities. Let me know your thoughts.