Login into Azure cli for a service principal - azure

I'm trying to get my ansible script to get logged into azure via azure cli. For some reasons, I'm not allowed to use the ansible azure package. I have to use the shell and call directly the commands from there.
I'm fairly new with azure in general, so all this tenants, service principals and such are still concepts that I don't fully grasp.
I've been checking official the documentation. I've created an app registration for it (Named ansible_test). I get all I need, including the secret. and then I call the the commands as this:
az login --service-principal -u $AZURE_SERVICE_PRINCIPAL_NAME -p $AZURE_SECRET --tenant $AZURE_TENANT
where:
$AZURE_SERVICE_PRINCIPAL_NAME = ansible_test
$AZURE_SECRET = ${The one that I've defined via Certificates & secrets section in the app registration}
$AZURE_TENANT = ${The azure tenant that I find in the app registration}
I'm getting the error:
Get Token request returned http error: 400 and server response: {"error":"unauthorized_client","error_description":"AADSTS700016: Application with identifier 'ansible_test' was not found in the directory '${AZURE_TENANT}(Blurred because I'm not sure this is something secret or not)'. 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.
As I understand, I got the wrong tenant. But I'm getting the exact one that I'm getting from the app registration. I've been hitting my head against this wall for some time. I've tried many other things, but it doesn't seem to work.
In this image, I'm trying to show that I've indeed created the app registration (What I'm understanding that it's a service principal). I've blurred the ids just out of ignorance whether they are private or not.
What is that I'm doing wrong? I can't really understand the origin of the error...

The username for a service principal is its Application (client) ID, so you need to use that instead of the app name.
It uses client credentials flow under the covers to get tokens which requires the client id, tenant id + client secret/client certificate to authenticate.

Use the following command, before running this command, make sure to define variables.
az login --service-principal -u ${app_id} -p ${password} --tenant ${tenant_id}

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.

AuthorizationFailed while using AZ CLI

Today I have tried to perform action on Azur ADF using CLI (Portal for that subscription can be only used as "read") AZ CLI is installed on AZ VM that via Managed identity has received Contributor role on the whole subscription. Running command ended with AuthorizationFailed.
After logging into AZ CLI with AZ login -i
and running command az datafactory configure-factory-repo
(AuthorizationFailed) The client 'CLIENT_ID' with object id
'CLIENT_ID' does not have authorization to perform action
'Microsoft.DataFactory/locations/configureFactoryRepo/action' over scope
'/subscriptions/SUBSCRIPTION_ID' or the scope is invalid.
If access was recently granted, please refresh your credentials.
Code: AuthorizationFailed Message: The client 'CLIENT_ID'
with object id 'CLIENT_ID' does not have authorization to
perform action 'Microsoft.DataFactory/locations/configureFactoryRepo/action' over scope
'/subscriptions/SUBSCRIPTION_ID' or the scope is invalid. If access
was recently granted, please refresh your credentials.
I have checked and VM Contributor role has Microsoft.DataFactory/locations/configureFactoryRepo/action
What else I should check?(I have no access to AZ AD)
Edit:
CLIENT_ID is equal to principalId of VM from which I'm running commands.
I assume that the CLIENT_ID and SUBSCRIPTION_ID actually are real values and you have replaced them to not disclose the here, correct?
To be sure that you are in the correct context you could first issue 'az account show' after you logged in using 'az login -i'. Is the response to that what you expected?
-- Edit --
The client ID should be the client id of the managed identity, also sometimes referred to as App ID (same thing). So when you log in with -i I believe it should be the same output as when you do the az account show. So that's a good thing.
Then I kind of get the feeling that it is a scope error. It looks a lot like you run in to this and it's by design as of now. But have a look at lmicverm's comment. You might use the the other call (Create or update Factory) as a workaround?

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

Azure Login Using Service Principal is failing with 401 - Invalid client secret provided

I have created a new application registration in my Azure Portal like so:
Home -> Azure Active Directory -> App registrations -> New Registration -> myApp.
I also created 3 different secrets for the app. Now I'm trying to log in via command line using one of those secrets like this:
az login --service-principal -u <Application (client) ID> -p <secret> --tenant <Directory (tenant) ID>
I'm getting the following error message: (key parts of the error only)
Get Token request returned http error: 401 and server response: {"error":"invalid_client","error_description":"AADSTS7000215: Invalid client secret is provided."error_codes":[7000215],"timestamp":"2021-06-01 20:59:28Z","error_uri":"https://login.microsoftonline.com/error?code=7000215"}
The Application (client) ID and Tenant ID values were taken from the "Overview" section of the Application registration.
Please check out the screenshot below.
If you can tell me where I've gone astray ... I'd appreciate it.
Thanks!
Made a new app registration, this worked for me: az login --service-principal -u client-id-here -p "client-secret-here" --tenant tenant-id-here.
When you create a client secret, you need to use the Value it gives you. You might then get an error because the app does not have access to any Azure resources. You can work around that with --allow-no-subscriptions if you need to do e.g. Azure AD management with Az CLI.

Azure Graph API: authorize application on multiple tenants

I am trying to create an application to browse my contacts directory on Exchange.
I have set up everything and I am able request the authorization from my app.
I can present the modal view, enter the login information, retrieve the token, but when I try to authorize the app with the same account I have created it I get this message:
The client <my app id> and resource <my app URI> identify the same application.
If I try to authorize another account, I receive this message instead:
User account <an email> from external identity provider <a url> is not
supported for application <my app id>
If I try to login on the Graph Explorer Console or on the Office 365 OAuth Sandbox, they work fine with the second address, but not with the first one.
I am really confuse. I feel like I have mess up some configuration option, but I don't really understand which one.
Regarding #1, please do not pass App ID of your application for resource querystring parameter when authenticating against your tenant URL. I ran into the exact same problem.
Then I ran WebApp-MultiTenant-OpenIdConnect-DotNet from Github and noted down the sign-in URL it created and I used the following:
var signInUrl = String.Format(
"https://login.windows.net/{0}/oauth2/authorize?response_mode=form_post&response_type=code+id_token&scope=openid+profile&client_id={1}&resource={2}&redirect_uri={3}&state={4}&nonce={5}",
Uri.EscapeDataString(tenantId),
Uri.EscapeDataString(clientId),
Uri.EscapeDataString("https://graph.windows.net"),
Uri.EscapeDataString(redirectUri),
Uri.EscapeDataString(state),
string.Format("{0}{1}", DateTime.UtcNow.Ticks, Guid.NewGuid().Stringify())
);
Basically I used https://graph.windows.net instead of App ID and magically things started to work :).
Another thing you could try (and I have not tried it) is authenticating against common endpoint https://login.windows.net/common/oauth2/authorize and provide your App ID for the resource querystring.

Resources