How can I identify what the "first party service" is when failing to authenticate to Azure KeyVault? - azure

Despite multiple hours of troubleshooting, I cannot get Visual Studio to authenticate to an Azure KeyVault. No matter what I try, I get the following unhelpful error:
Service request failed.
Status: 403 (Forbidden)
Content:
{"error":{"code":"Forbidden","message":"Access denied to first party service.\r\nCaller: name=from-infra;tid=GUID_REDACTED;appid=GUID_REDACTED;iss=https://sts.windows.net/GUID_REDACTED/\r\nVault: VAULT_NAME;location=westus","innererror":{"code":"AccessDenied"}}}
Is there anything in here (maybe one of the redacted GUID values) I can use to determine what the "First Party Service" it is having a problem with is?
I am signed in with my MSDN account in the "Azure Service Authentication" section. The KeyVault exists in that MSDN account. There are also Access policies in that KeyVault for both my MSDN account and the principal ID of my App Service. These appear to be completely ignored when trying to authenticate.
Here is the basic code I have been trying to use.
var credential = new VisualStudioCredential(new VisualStudioCredentialOptions { TenantId = "GUID from tid in above error" });
// Create a secret client using the DefaultAzureCredential
var client = new SecretClient(new Uri("https://MY_VAULT.vault.azure.net/"), new DefaultAzureCredential());
var secret = client.GetSecret("MySecretId");
I have tried multiple versions of the VisualStudioCredential and DefaultAzureCredential. No matter what I do, I cannot get away from this "Access denied to first party service" error, so I think the next step is to find out what the "first party service" is, because it does not seem to be my MSDN account nor my App Service.

Tenant f8cdef31-a31e-4b4a-93e4-5f571e91255a is a special tenant where Microsoft first party applications are defined. Certain ARM and Compute scenarios access Key Vault using tokens from this tenant, but in general Key Vault rejects tokens from this tenant and it is not available for use by customers.
The tenant you should use is the one that shows up under "Tenant ID" when you look at the "Azure Active Directory" section in the Azure Portal. Personal accounts, such as outlook.com accounts, can get tokens issued by the first party tenant if they do not specify their own tenant ID. Organization accounts get tokens from their home tenant based on the verified domains associated with the tenant, so they generally do not need to specify a tenant ID explicitly.

Related

How to get access token for subscription in a different tenant?

I'm trying to use "invoke an http request" action in power automate to query a log analytics workspace. I have access to perform this from azure portal. I referred this Microsoft article to get the URI. But when I try to execute the flow, I get the below error:
Complete error message:
{
"error": {
"message": "The provided authentication is not valid for this resource",
"code": "InvalidTokenError",
"correlationId": "45e0ff0c-01f1-4ea5-a11d-ec6ce2d71b8b",
"innererror": {
"code": "InvalidAuthenticationTokenTenant",
"message": "The access token is from the wrong issuer 'https://sts.windows.net/687f51c3-0c5d-4905-84f8-97c683a5b9d1/'. It must match one of the tenants 'https://sts.windows.net/2f4a9838-26b7-47ee-be60-ccc1fdec5953/,https://sts.windows.net/a6eb2ff5-3009-4bfc-b769-24a2f82c1913/' associated with this subscription. Please use any authority (URL) from 'https://login.windows.net/2f4a9838-26b7-47ee-be60-ccc1fdec5953,https://login.windows.net/a6eb2ff5-3009-4bfc-b769-24a2f82c1913' to get the token. Note, if the subscription is transferred to another tenant there is no impact to the services, but information about new tenant could take time to propagate (up to an hour). If you just transferred your subscription and see this error message, please try back later."
}
}
}
The analytics workspace that I'm trying to query is not under my AAD tenant. It is under another tenant/directory, which I have access from portal. How can I get the access token so that I can execute this query?
I have already tried the action "Run query and list results" in power automate, which gave the same error.
Any suggestions?
Please check below points:
Please check if you have multiple subscription .So while
requesting access token , it is the tenant which is not part of the
subscription that you might have selected. In such a case try to
change the settings and make your subscription map to the directory
which you want to use.
In some cases browser tries or attempts to get an access token from
already logged in tenant .So If its under same subscription, try to
check after clearing the cache
You can also put required tenant ID in the enviroment settings of
your particular app, using DefaultAzureCredential()
Or Configure the authority defining the tenantId
https://login.microsoftonline.com/{tenant-id} for multiple tenants
Signing in once to access to all the Azure Log Analytics data from
all tenant may not be feasible.It may require reauthentication .
Check this way to get
the accesss token for that particular tenant Request an
authorization token - Azure Monitor | Microsoft Docs and use the
token to call the log analytics workspace
References:
Query - Execute - REST API (Azure Log Analytics) | Microsoft Docs
azure log analytics - Valid authentication was not provided - Stack
Overflow

Unable to get access token. 'AADSTS500011: The resource principal named 'xxx' was not found in the tenant -tenantid

I am trying to get the access token for the Azure function app. I have enabled managed identity for the function app(system assigned). but while fetching the token using the nuget Azure.Identity.
var tokenCredential = new DefaultAzureCredential();
var accessToken = await tokenCredential.GetTokenAsync(
new TokenRequestContext(scopes: new string[] { "https://xxx.azure-api.net/" + "/.default" }) { }
);
I am getting the error.
The resource principal named 'xxx.azure-api.net' was not found in
the tenant 123
but when run az cli to check the subscription details, the subscription indeed part of the tenant 123 only.
Here is what I have finally done.
I have registered an App in AD. and Exposed the API of that App.
I have assigned System Assigned Managed Identity to the Function.
In the local I am not able to request token because Azure CLI is not given consent.
After deploying the application in Function my Function app can request a token using its identity.
You need to register the application in azure ad and enable the access token. Once that is done the you need to provide RBAC access to your xxx.azurewebsites.net
Follow this article for the step by step documentation Microsoft Document Reference
Unfortunately, the error message is not really helpful. But adding a scope to the app registration solved the problem for me:
In Azure Portal navigate to App Registrations
Find your app, in the left side menu select Manage => Expose an API
Add a scope. I named mine api_access as this was where this error occurred.
In my case I then got an API URI (like api://client-id/scope_name) which I used in my Angular app. Error message was gone.
Also, make sure that in the Enterprise Application you have created, under Manage => Properties, "Assignment required" and "Visible to users" is turned on.

Use a certificate in the keyvault to access multi-tenant application in other tenant

We have a multi-tenant application in our Azure AD tenant. It is authorized in some other tenants (we know which ones). And it has multiple certificates registered to it to be used as client credentials.
We want to remove the certificates from the local stores and use a certificate in the key vault to request a token for one of the external tenant. According to the documentation this is one of the use cases.
Our tenant (id: xxxx):
Has app registration (app id: abcd-xxx-xxxx-xxx)
has keyvault
has managed service principal (with access to the key vault)
other tenant (id: yyyy):
Executed Admin consent for our application.
Question 1:
How do I create a certificate in the Key vault that is connected to an existing application (app id: abcd-xxx-xxxx-xxx)? It is important to note that since the application is already approved by several third party admins, it cannot be recreated. Same counts for creating a new certificate after it would be expired.
Question 2:
How to I setup the Microsoft.Azure.Services.AppAuthentication library to:
Use the managed identity to access the key vault in our tenant (xxxx).
Use the certificate in the key vault to request a token for our app (abcd-xxx-xxxx-xxx) in other companies tenant (yyyy)
Answer 1:
You could use az ad sp credential reset command like below. If you don't want to overwrite the existing certificate of the App, please pass the --append parameter.
az ad sp credential reset --name '<application-id>' --keyvault joykeyvault --cert cer136 --create-cert --append
Answer 2:
1.To use the MSI access the keyvault in your tenant, just use the code below.
No code changes are required, when you run your code on an Azure App Service or an Azure VM with a managed identity enabled, the library automatically uses the managed identity, see this link.
The environment variable AzureServicesAuthConnectionString has to be set to any credential with access to the keyvault. RunAs=Developer; DeveloperTool=AzureCli for dev or RunAs=App; for managed service identity (automatically in azure).
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Azure.KeyVault;
// Instantiate a new KeyVaultClient object, with an access token to Key Vault
var azureServiceTokenProvider1 = new AzureServiceTokenProvider();
var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider1.KeyVaultTokenCallback));
2.If you want to use the service principal along with its certificate stored in the keyvault to get the token for the resources in another tenant, the connection string on the AzureServiceTokenProvider has to be set to RunAs=App;AppId={TestAppId};KeyVaultCertificateSecretIdentifier={KeyVaultCertificateSecretIdentifier} then you can get tokens for other tenants like.
const string appWithCertConnection = "RunAs=App;AppId={TestAppId};KeyVaultCertificateSecretIdentifier=https://myKeyVault.vault.azure.net/secrets/myCert";
Then use the code to get the token, e.g. for the resource https://management.azure.com/.
var azureServiceTokenProvider2 = new AzureServiceTokenProvider(appWithCertConnection);
string accessToken = await azureServiceTokenProvider2.GetAccessTokenAsync("https://management.azure.com/", "tenant-id-of-thridh-party-tenant").ConfigureAwait(false);

Access denied linking variable group to key vault in VSTS

When I try to link a variable group to key vault in VSTS, every time I select my endpoint, it tells me:
"Specified Azure endpoint needs to have "Get, List" secret management permissions on the selected key vault. Click "Authorize" to enable VSTS to set these permissions or manage secret permissions in Azure portal."
It makes no sense. That specific endpoint has Get and List for secrets, keys, certificates. The endpoint is using the correct Service Principal Client ID- I know because I pulled its corresponding app registration up in Azure by searching with that ID. And the app registration is specifically listed in the key vault's Access policies, with the correct permissions.
Trying to click "Authorize" in VSTS just give me
"Resource not found for the segment 'DirectoryDataService.getServicePrincipalsByAppIds'. For troubleshooting refer to https://go.microsoft.com/fwlink/?linkid=835898"
and the endpoint is broken until I re-verify it.
I'm kind of at my wit's end here- everything is set exactly as https://learn.microsoft.com/en-us/vsts/build-release/concepts/library/variable-groups?view=vsts says it should be.
Edit: Turns out the Azure tried to add the app reg as a person instead of an app when I listed it in the ARM template by object ID (app ID most definitely does not work there). So now I just need to figure out how to add it as an application in the ARM template...
Edit Edit: Soooo... the Object ID the Azure Portal shows for an App Registration? That's not the Object ID the ARM template wants. It wants the... I'm not sure what you'd call it. In Powershell, you use it with -Object ID, but when you list the properties, it's under "Id". Whatever. To get it, you run
Get-AzureRmADServicePrincipal -SearchString "[your-app-reg-name]"
And it shows up under Id. That's what you want to use as an object ID in your ARM template.
According to the error Resource not found for the segment 'DirectoryDataService.getServicePrincipalsByAppIds, the issue seems more related to Azure side.
To access azure-keyvault you need four things :
- clientId = "<client id of your application registed on Azure AD>";
- domain = "<your talnet id>";
- secret = "<client key of your application registed on Azure AD>";
- subscription = "<your subscription id>";
Then these will combine ApplicationTokenCredentials, finally Authorize to KeyVaultClient . Suggest you take a look at this question: Azure keyvault client 1.0.0 initiate client
Besides also double check/confirm the specific endpoint has Get and List for secrets, keys, certificates.

Azure AD - Add app principal to a Group

I have an Azure AD app (AAD App1) which has user assignment enabled. So only, users from a particular group let's say "Group A" can access any resource (let's say an Azure Function API) protected by that Azure AD app.
Now I have another daemon Azure function job, which needs to make an authenticated call to the above mentioned Azure function API. Since this is a daemon job, I have generated another Azure AD app (AAD App2) for this.
Below is my code to get access tokens:
string resourceId = "id of app used to authenticate azure function"; // AAD app ID used by the Azure function for authentication
string clientId = "id of app registered for the daemon job";// AAD app ID of your console app
string clientSecret = "secret of app registered for the daemon job"; // Client secret of the AAD app registered for console app
string resourceUrl = "https://blahblah.azurewebsites.net/api/events";
string domain = "<mytenant>.onmicrosoft.com"; //Tenant domain
var accessToken = await TokenHelper.GetAppOnlyAccessToken(domain, resourceId, clientId, clientSecret);
Now when I try to generate access token to access the Azure function API, I get an invalid grant error as below:
AdalException:
{"error":"invalid_grant","error_description":"AADSTS50105: Application
'' is not assigned to a role for the application
''.\r\nTrace ID:
6df90cf440-c16d-480e-8daf-2349ddef3800\r\nCorrelation ID:
4c4bf7bf-2140-4e01-93e3-b85d1ddfc09d4d\r\nTimestamp: 2018-05-09
17:28:11Z","error_codes":[50105],"timestamp":"2018-05-09
17:28:11Z","trace_id":"690cf440-c16d-480e-8daf-2349ddef3800","correlation_id":"4c4bf7bf-2140-4e01-93ef3-b85d1dc09d4d"}:
Unknown error
I am able to properly generate AAD access tokens if I disable the user assignment.
I am trying to avoid creating a service account here. Is there anyway I can add an app principal to an Azure AD group or add it as a member of another Azure AD app?
Unfortunately, you cannot add an AAD application/service principal as a member of Azure AD group.
I have confirmed this issue in My Answer for another similar question [EDIT - now seems to be possible, see said answer]
You can also upvote this idea in our Feedback Forum. Azure AD Team will review it.
Hope this helps!

Resources