I'm trying to use a User Assign Managed Identity to retrieve access in KeyVault reference in Azure Function.
I'm following this doc https://learn.microsoft.com/en-us/azure/app-service/app-service-key-vault-references?tabs=azure-cli#:~:text=you%20haven%27t%20already.-,Configure,-the%20app%20to to reference the keyvault in the application configuration.
I followed these steps:
Created User Assign Managed Identity.
Created a policy in Keyvault and gave permissions GET and LIST to User Assign Managed Identity.
Set the User Assign Managed Identity in Azure Function Identity
Set properties application setting like this:
mysecureapp - #Microsoft.KeyVault(SecretUri=https://mykv.vault.azure.net/secrets/mysecret/id)
keyVaultReferenceIdentity - /subscriptions/subsid/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/mgid
Any thoughts on this?
I realized that in addition to setting the property keyVaultReferenceIdentity via app-setting, we need to change this property of the same name in the resource function. The default value is SystemAssign if you enable it. Unfortunately the MS documentation is unclear on this.
I found the property that can be used in the terraform documentation, follow the link: https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/function_app#:~:text=key_vault_reference_identity_id
After setting this property to the value of User Assign Managed Identity this worked fine.
just found that when the keyVaultReferenceIdentity property is created in the Function using the portal our IaC (App Settings), it doesn't recognize the User Assigned identity as the one to authenticate in KeyVault, but if you run the PATCH described in the following link using PowerShell, it works.
https://learn.microsoft.com/en-us/azure/app-service/app-service-key-vault-references?tabs=azure-powershell#access-vaults-with-a-user-assigned-identity
it should be enough to the reference to KeyVault works
wow !
I'm also searching the same topic for user identity and the same issue.
I just followed the marked answer , its worked and able to retrieve the value.
Thanks # Magno Oliveira to bring this question to the community.
just need to run the CLI command in azure portal ! give resource group name and useridentity name and function app name to the below command
userAssignedIdentityResourceId=$(az identity show -g resourcegroupname -n manageidenityname --query id -o tsv)
appResourceId=$(az webapp show -g resourcegroupname -n functionappname --query id -o tsv)
az rest --method PATCH --uri "${appResourceId}?api-version=2021-01-01" --body "{'properties':{'keyVaultReferenceIdentity':'${userAssignedIdentityResourceId}'}}"
I hope you already done all the steps. But one thing you may missed i.e.,
you have to enable the system-assigned identity for your application.
This error MSINotEnabled comes mostly during the absence of a managed Identity for your application, and it clearly says i.e., System assigned Managed identity.
Refer to this medium article where we will find the troubleshooting steps had given along with all these kind of errors with resolutions were described.
Related
As said in title I'm facing a permission/privilege issue.
I've logged to az-cli using a service principle I created with Contributor role.
Now, this SP is used in a pipeline, where it needs to edit access policies of a KeyVault for another SP (that has no roles).
I'm using
az keyvault set-policy -n testserviceprincipal --secret-permissions list --spn <id>
but i get Insufficient privileges to complete the operation.
I tried to add keyvault prmissions but still missing something.
Did someone had the same issue and managed to resolve?
I'm somehow sure I'm missing some permissions like user.read cause if I use --object-id and the ObjectId of SP all works fine.
Thanks in advance!
I can understand the meaning of red & green icons of Azure key vault reference come in configuration on Azure portal, but couldn't found the meaning of blue icon (shown in snapshot below).
Any help
I had this issue when trying to use "User Assigned Managed Identities".
It appears that App Services will automatically use the "System Managed Identity" for Key Vault References, even if there is none configured.
You can however tell Azure to use a specific managed identity using Azure CLI or Powershell (or bicep) by setting the "keyVaultReferenceIdentity" as documented here:
https://learn.microsoft.com/en-us/azure/app-service/app-service-key-vault-references?tabs=azure-cli#access-vaults-with-a-user-assigned-identity
userAssignedIdentityResourceId=$(az identity show -g MyResourceGroupName -n MyUserAssignedIdentityName --query id -o tsv)
appResourceId=$(az webapp show -g MyResourceGroupName -n MyAppName --query id -o tsv)
az rest --method PATCH --uri "${appResourceId}?api-version=2021-01-01" --body "{'properties':{'keyVaultReferenceIdentity':'${userAssignedIdentityResourceId}'}}"
Once I updated this, the blue icon changed to that magical green checkbox! ;-)
Green means it was able to perform the authentication / retrieve the secret.
Red means there's something wrong. (It can be a network security rule for example)
No marks, probably it's not using Key Vault References
I designed a PowerShell script that it's able to properly configure various settings of a Function App (including CORS e.g.).
The Function App works and can be called from an Api Manegement service.
When the need arose to configure Azure AD, I've used Az/CLI to replicate exactly what I do using Portal UI (and what I set manually perfectly works).
But it stopped working, APIM returns HTTP status code 401 (unauthorized).
The part of the script that configures Azure AD is the following:
# $add is a simple class that contains value to be configured
# actually AllowedTokens is always empty
if ($aad) {
'Setting Function App AAD configuration.' | Write-Verbose
$allowedTokens = if ($aad.AllowedTokens) { "--aad-allowed-token-audiences $($aad.AllowedTokens -join ' ')" } else { '' }
"az webapp auth update --name $name --resource-group $group --enabled $($aad.Enabled.ToString().ToLower())" +
" --action LoginWithAzureActiveDirectory --aad-client-id $($aad.ClientId) --aad-client-secret $($aad.ClientSecret)" +
" --token-store true" +
" --aad-token-issuer-url $($aad.TokenIssuerUrl) $allowedTokens" |
Invoke-Expression
'Function App AAD configuration set.' | Write-Verbose
}
The first strange thing is that if I disable authentication/authorization,
I save settings, enable and save again everything start working.
So I've started again and launched the script. I've examined the resource.
az auth show says that unauthenticatedClientAction is set to RedirectToLoginpage.
az resource show says that unauthenticatedClientAction is set to null.
When I do the trick described above:
az auth show says that unauthenticatedClientAction is set to AllowAnonymous.
az resource show says that unauthenticatedClientAction is set to null.
So I think this is the important difference to make the Function App properly works (or better this is the way to properly configure it).
Since I've used this method with success for other settings, I've tried to set this property with Az/CLI:
az resource update --name web --resource-group $group --namespace Microsoft.Web --resource-type config `
--parent "sites/$funcName" --set properties.siteAuthSettings.unauthenticatedClientAction=AllowAnonymous
The JSON returned as response shows nothing changed. Inspecting the resource confirms it.
One more thing, when I export the resource group I can't see any unauthenticatedClientAction in any Function App template.
What's the correct way to set unauthenticatedClientAction to AllowAnonymous?
Any help will be really appreciated!
First, answer your question, to set unauthenticatedClientAction to AllowAnonymous, just use
az webapp auth update --name <functionapp-name> --resource-group <group-name> --action AllowAnonymous
Actually, when you do the trick in the portal, it will change the
to
This is the unauthenticatedClientAction setting.
Then the question is coming, I am not sure if you want to secure your azure function with Azure AD or not. Because when you set unauthenticatedClientAction to AllowAnonymous, your function will allow the anonymous request, the Azure AD auth will not take effect.
When the need arose to configure Azure AD, I've used Az/CLI to replicate exactly what I do using Portal UI (and what I set manually perfectly works). But it stopped working, APIM returns HTTP status code 401 (unauthorized).
Yes, the 401 error represents the Azure AD auth toke effect, if you enable the Azure AD auth(set Log in with Azure Active Directory), you need to get the access token for your client/user, then use the token to access the function. (Not sure how to implement it in APIM, I am not an expert in APIM:-))
For more details, you could check this blog and this post.
I am using Azure app service api to view server details like worker process and region etc. for management purpose. After generating token from AuthenticationContext.AcquireTokenAsync method, I am requesting following URL for server details https://management.azure.com/subscriptions/<sub ID>/resourceGroups/<resource group name>/providers/Microsoft.Web/serverfarms/?api-version=2018-02-01
In the response I am getting AuthorizationFailed error code with the detail given bellow:
The client does not have authorization to perform action 'Microsoft.Web/serverfarms/read' over scope '/subscriptions/xxxxxxxx-xxxxxxx-xxxx/resourceGroups/xxxxxxxxxxx/providers/Microsoft.Web/serverfarms/xxxx' or the scope is invalid. If access was recently granted, please refresh your credentials.
But when I try the same verification using https://learn.microsoft.com/en-us/rest/api/appservice/appserviceenvironments/get portal where I can try the APIs for testing, the request is returning expected results.
So, is there any other way to authenticate or should I have to define some permissions to achieve the functionality?
The service principal you are using doesn't have rights within that tenant.
Tenants have subscriptions and service principals belong to tenants. Azure resource manager also exposes role based authorization for a given principal, which would give it rights on Azure resources. It appears the service principal doesn't have rights to read from that subscription.
Go to portal and find your subscription, click on Access Control (IAM) and then click on Add role assignment with correspond service principal which you use to acquire token.
After you have given successful permission, refresh and try again.
I had the same error while running,
az aks get-credentials --resource-group myResourceGroup --name myAKSCluster
I did this shortly after az login.
Problem was I haven't set my subscription properly so what I had to do was run,
az account set --subscription your-subscription-id
After that az aks get-credentials worked fine, the error was gone and you will get an output like,
Merged "myAKSCluster" as current context in C:\Users\UserName\.kube\config
I had the same problem. Initially, I went ahead and added to my user the "Web Plan Contributor" role, as it is the one that should handle those things. Nothing changed - I still had this error.
What turned actual problem turned out to be is a wrong resource group... Turns out I copied some old script where WebAppPlans were in separate RG, and I was searching the app plan there. Completely missleading error. I guess it will bring up the same error message even if the App Plan simply doesn't exist.
I want to give an Azure Managed Identity access to the Graph with Directory.Read.All. I was able to get it to work by following this blog: https://blog.bredvid.no/accessing-apis-using-azure-managed-service-identity-ff7802b887d?gi=f2307752395a, however:
that throws an Authorization_RequestDenied error (though apparently expected: MSI Permissions for Graph API)
I would prefer to get this working under az-cli
I tried...
graphId=$(az ad sp list --filter "appId eq '00000003-0000-0000-c000-000000000000'" --query "[0].objectId")
roleId=$(az ad sp list --filter "appId eq '00000003-0000-0000-c000-000000000000'" --query "[0].appRoles[?value=='Directory.Read.All' && contains(allowedMemberTypes, 'Application')] | [0].id")
az role assignment create --role $roleId --assignee-object-id fa22d971-c442-41f2-add1-77e636f80d31 --scope $graphId --assignee-principal-type MSI
But this results in... "The request did not have a subscription or a valid tenant level resource provider."
I am thinking this means I don't have the scope right. Is it possible to do this assignment under az-cli?
It is not possible to assign a service principal(MSI) to an application role currently, all commands here.
The az role assignment create is to add the user/service principal/group to the azure resource as an RBAC role, not that you want, it equals the steps in this link.
Besides, if you want to use the azure CLI instead of powershell because of the cross-platform issue. You could try the powershell core, it is cross-platform, refer to this link to install AzureAD.Standard.Preview module in it, then you will be able to use the AzureAD commands.