Azure : Permission for Service Principal to get list of Service Principals - azure

I am using the Fluent Azure SDK for .NET to try fetching the list of all service principals in the tenant.
var authenticatedContext = Azure.Authenticate(
await SdkContext.AzureCredentialsFactory.FromServicePrincipal(aadClientId, aadClientSecret, tenantId, "AzureGlobalCloud")
);
var sps = authenticatedContext.ServicePrincipals.ListAsync().GetAwaiter().GetResults();
The service principal with the AAD Client Id has Directory.Read.All API permission.
(Just to be sure I'm not missing anything : I see this permission in ServicePrincipal -> Permissions section in the Azure Portal)
But still, the following error is thrown :
Microsoft.Azure.Management.Graph.RBAC.Fluent.Models.GraphErrorException: Operation return an invalid status code 'Forbidden'
However, the callouts to get ADGroup and list of subscriptions work
var subs = authenticatedContext.Subscriptions.ListAsync().GetAwaiter().GetResults();
var sgs = authenticatedContext.Subscriptions.ActiveDirectoryGroups().GetByIdAsync(someId).GetAwaiter().GetResults();
I don't know what permissions are missing.

I test the code in my side, and use fiddler to catch the request. It seems the sdk request Azure AD graph api but not Microsoft graph api to list the service principals. So you need to add permission Directory.Read.All of AAD graph but not Microsoft graph. Please refer to the steps below:
After adding the permission, do not forget grant admin consent for it. Then you can run your code success to get the service principal.
By the way, there is a bug with AAD permission Directory.Read.All. If we add AAD permission Directory.Read.All into the registered app, then the permission can not be removed even if we remove it from the page. So you still can run the code success even if you remove the Directory.Read.All from "API permissions" tab on the page.

Related

How can I grant consent to my own app in azure, in case I am not global admin in tenant?

Given I have created an app using this repository in Azure.
And this app is deployed using a Service Principal which was created by below command:
az ad sp create-for-rbac --name "fxpricepredictor" --role contributor --scopes "/subscriptions/YOUR-SUBSCRIPTION-ID/resourceGroups/YOUR-RESOURCE-GROUP-NAME" --sdk-auth
Now, I need to get the API token to manage my created resources using REST APIs.
Based on documentation, I should be able use my tenantId, clientId and client_secret to get the token by calling the bellow endpoint:
curl: POST
https://login.microsoftonline.com/{{tenantId}}/oauth2/token
Please notice that, I am not the global admin in the tenant.
The official sample postman collection is here and here is how my request looks like in postman:
Sadly the endpoint does not provide me the token and instead it returns such error:
{
"error": "unauthorized_client",
"error_description": "AADSTS700016: Application with identifier 'MY_CLIENTID' was not found in the directory 'MY COMPANY'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.\r\nTrace ID: 5a9a2c53-c3c8-46da-a1a6-551b42082400\r\nCorrelation ID: bf7c5966-ffa4-4312-8a77-434c2560d65a\r\nTimestamp: 2022-10-05 14:54:23Z",
"error_codes": [
700016
],
"timestamp": "2022-10-05 14:54:23Z",
"trace_id": "5a9a2c53-c3c8-46da-a1a6-551b42082400",
"correlation_id": "bf7c5966-ffa4-4312-8a77-434c2560d65a",
"error_uri": "https://login.microsoftonline.com/error?code=700016"
}
please notice, I hided some sensitive values in error response by MY_CLIENTID and MY COMPANY
So, i guess, the main reason that i am facing this issue is that:
This can happen if the application has not been consented to by any user in the tenant.
Meaning that, i should consent my own app. Am I right ?
So, my question is:
How can i get the token to work with REST APIs to manage my resources ?
How can I grant consent to my own app, given that I am not a global Admin ?
Update:
As I figured out, I should be able to Grant Consent to my app using "Microsoft Graph permissions reference". And here is what i have done:
Login to Azure portal
Navigate to "Azure Active Directory"
Navigate to "App registrations"
Click on the created APP ("fxpricepredictor")
Navigate to "API permissions"
Click "Add a permission"
Click on "Microsoft Graph"
Choose "Delegated Permissions"
Search for "authentication" ---> (Sadly this option also requiereds Admin Consent)
I tried to reproduce the same in my environment and got the below results:
When I ran the same command as you, one Azure AD application named fxpricepredictor is automatically created with details like below:
az ad sp create-for-rbac --name "fxpricepredictor" --role contributor --scopes "/subscriptions/<subscriptionID>/resourceGroups/<resourcegroupName>" --sdk-auth
By including above details as parameters, I am able to generate access token successfully via Postman like below:
Please note that, I don't have global administrator role and granting admin_consent is not really required.
With the above access token, I am able to fetch and manage the Azure resources in that resource group like below:
GET https://management.azure.com/subscriptions/<subscriptionID>/resourceGroups/SriTest/resources?api-version=2021-04-01
Response:
The error AADSTS700016 may also occur if there is no application in your tenant with provided ClientID.
I tried including random ClientID which does not exist in Azure AD tenant and got same error as below:
So, make sure to check whether the application is existing or not with the given ClientID in Azure AD tenant.

Microsoft Azure OAuth Client Credentials Token gets "AuthorizationFailed" response

I want create APIM subscriptions through rest api, And was able to do it successfully by following this Microsoft doc, https://learn.microsoft.com/en-us/rest/api/apimanagement/current-ga/subscription.
And for Authentication I am generating a bearer token using ROPC grant type(My UserName & Password). Everything works fine with this flow.
But i dont want to configure my username & password in a application to get a bearer token, instead i followed Client-Credentials grant type(get token by client id & secret), i am able to generate token, but when i use that token to create subscription in APIM, i am getting a exception
The client '0--e' with object id '0--e' does not have authorization to perform action 'Microsoft.ApiManagement/service/subscriptions/write'
Is it possible to add a AAD application inside APIM AccessControl(IAM) to grant permission.
Or is this any other way to do this? or ROPC is the only way?
Can someone please help.
Yes, you can grant permission to AAD application (service principal) in APIM Access Control (IAM) by assigning it API Management Service Contributor role.
I tried to reproduce the same in my environment and got the below results:
I have generated one access token using Client-Credentials grant type like below:
When I used the above token to create APIM subscription with below query, I got the same error:
PUT https://management.azure.com/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.ApiManagement/service/apimService1/subscriptions/testsub?api-version=2021-12-01
{
"properties": {
"ownerId": "/subscriptions/subid/resourceGroups/rgname/providers/Microsoft.ApiManagement/service/servicename/users/xxxxxxxxxxx",
"scope": "/subscriptions/subid/resourceGroups/rgname/providers/Microsoft.ApiManagement/service/servicename/products/xxxxxxxxxxx",
"displayName": "testsub"
}
}
Response:
To resolve the error, you need to grant API Management Service Contributor role for that application like below:
Go to Azure Portal -> APIM Services -> Your APIM -> Access control (IAM) -> Add role assignment
After granting the above role, I generated the access token again and ran the same query as below:
PUT https://management.azure.com/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.ApiManagement/service/apimService1/subscriptions/testsub?api-version=2021-12-01
Response:
When I checked the Portal, APIM subscription got created successfully like below:
Reference:
How to use Role-Based Access Control in Azure API Management | Microsoft Docs

The client 'XXX' with object id 'XXX' does not have authorization to perform action 'Microsoft.Media/mediaServices/transforms/write'

I am trying to use the following git repo in order to connect to azure ams, upload a video and stream it:
https://github.com/Azure-Samples/media-services-v3-node-tutorials/blob/main/AMSv3Samples/StreamFilesSample/index.ts
For some reason I am keep getting the following error:
The client 'XXX' with object id 'XXX' does not have authorization to perform action 'Microsoft.Media/mediaServices/transforms/write' over scope '/subscriptions/XXX/resourceGroups/TEST-APP/providers/Microsoft.Media/mediaServices/TESTAMP/transforms/ContentAwareEncoding' or the scope is invalid. If access was recently granted, please refresh your credentials
The AD user is owner but I understand it is a permission issue.
I searched all over the web for hours what permission do I need to grant and where but could not find any solution
The error get thrown here:
let encodingTransform = await mediaServicesClient.transforms.createOrUpdate(resourceGroup, accountName, encodingTransformName, {
name: encodingTransformName,
outputs: [
{
preset: adaptiveStreamingTransform
}
]
});
of course, I have updated the .env file to the correct data of my azure account.
Can anyone point out what am I missing and how to grant this permission?
Thanks!
The error message is referring to your Service Principal that is being used to authenticate against the AMS SDK.
Double check that you entered the GUID values for the service principal ID and Key, and make sure you did not use the friendly name in there.
AADCLIENTID="00000000-0000-0000-0000-000000000000"
AADSECRET="00000000-0000-0000-0000-000000000000"
Also, double check in IAM Access control in the portal that the service principal exists under the Role Assignments for your Media Services account and has Contributor or Owner permission Role first.
If you are in an Enterprise that locks down AAD access - you may need to work with your AAD owner/admin to make these changes and grant the service principal the right roles for your account. That's a bit outside of Media Services, and is just general Azure AAD application creation rights, and role assignments.
If you are still hitting issues, I would file a support ticket and also ask your AAD administrator to assign the role permisssion to your service principal.
As an aside, we are also working on updated Node.js SDK samples for the upcoming (soon!) release of the 10.0.0 Javascript SDK.
See the beta samples here - https://github.com/Azure-Samples/media-services-v3-node-tutorials/tree/10.0.0-beta.1

Getting error "Insufficient privileges to complete the operation" while pulling application list using azure-python-sdk

I'm using a service principle with permissions Application.Read.All and Directory.Read.All of Application type to authenticate to Azure and using following code to pull list of Applications in the tenant.
from azure.common.credentials import ServicePrincipalCredentials
from azure.graphrbac import GraphRbacManagementClient
from config import app
credentials = ServicePrincipalCredentials(
client_id = app["CLIENT"],
secret = app["KEY"],
tenant = app["TENANT_ID"],
resource="https://graph.windows.net"
)
graphrbac_client = GraphRbacManagementClient(credentials, app["TENANT"])
for app in graphrbac_client.applications.list():
print("\nApp:")
print(app)
print("******\n")
Any help is much appreciated
Application.Read.All and Directory.Read.All these 2 permissions requires Global Administrator consent for your directory. I would suggest to ask your Global Administrator to provide consent to your service principal.
From your description, I suppose you added the application permission Application.Read.All and Directory.Read.All of Microsoft Graph, because what you need is Azure Active Directory Graph, which does not have the Application.Read.All permission.
In your code, it uses the resource="https://graph.windows.net", which means your code calls the Azure Active Directory Graph, not Microsoft Graph, to solve the issue, just add the application permission Directory.Read.All of Azure Active Directory Graph like below.
Note : After adding the permission, don't forget to click the Grant admin consent for xxx button, otherwise your service principal will not get the permission.
There may be some delay, after half an hour, test the code, it works fine.

Azure Admin Consent in multi tenant not working

I've some problems with the admin consent in a multi tenant environment.
So here is my structur.
Tenant 1
Tenant 2
I've got registered one ActiveDirectory Aapp in Tenant 1, called "App1".
In this App, I set i.e. permissions for Microsoft Graph.
Then I granted this permission.
Now I want to have also this App1 in my Tenant 2, so I do an AdminConsent with:
https://login.microsoftonline.com/TenantID_of_Tenant2/adminconsent?client_id=ClientID_of_App1
It worked fine. A few minutes later I saw App1 in Tenant2 and I was able i.e. to give access right to App1 for Users of Tenant2. No problem.
So then I had to give my App1 a few more permissions. So I clicked
"App registrations" in Tenant1 and gave more permissions for Microsoft Graph.
Then I clicked to "Enterprise Applications" in Tenant1, selected my App1 -> Permission and then "Grant admin consent for tenant1". A new browser was opened and I was able to do the admin consent for App1 in Tenant1.
Then I thought that I have to do the same in Tenant2, because it works the first time. So in Tenant2 I also navigated to ActiveDirectory -> Enterprise Applications -> selected my App1 -> Permissions
Here I saw the first permissions which I granted. Then I clicked to "Grant admin consent for Tenant2". A new browser was opened, but now it failed with folowwing error:
https://myRedirectURL/?error=access_denied&error_description=AADSTS65005%3a+The+application+%clientID_of_App1%27+asked+for+permissions+to+access+a+resource+that+has+been+removed+or+is+no+longer+available.+Contact+the+app+vendor.%0d%0aTrace+ID%TraceID%0d%0aCorrelation+ID%CorrelationIDaTimestampTimestamp&admin_consent=True&tenant=TenantID_of_Tenant2
Better to read: Error:
"AADSTS65005. The application ID_App1 asked for permissions to access a resource that has been removed or is no longer available. Contatct the app vendor."
I get the same error when I invoke the URL https://login.microsoftonline.com/TenantID_of_Tenant2/adminconsent?client_id=ClientID_of_App1
But I didn't do anything...so wheres the problem?
For your Redirect URI error you can try these steps:
Set the resource in your request to Azure AD.
Ensure that the client Id of the WebApp is configured in the WebApi's "knowClientApplications" array property in the manifest file
Ensure that all permissions are correct (APIs are added as delegated permissions to the client).
Ensure that all services (web app & apis) are multi tenant
Update manifest with:
"availableToOtherTenants": true,
"knownClientApplications": [
"{client app application id}"
],
See also the troubleshooting steps in these similar threads:
Azure AD error when fetching access token & login
The client application has requested access to resource 'https://outlook.office365.com'. This request has failed

Resources