AzureCliCredential giving error, Please run 'az login' to set up account - asp.net-core-3.1

I am using ChainedTokenCredential and trying to get managed identity token in local debug environment using Visual Studio 2019. In windows terminal I already logged in using Azure CLI az login.
var credential = new ChainedTokenCredential(
new ManagedIdentityCredential(),
new AzureCliCredential());
var token = await credential .GetTokenAsync(new TokenRequestContext(new[] { _configuration.GetSection("scope").Value }));
When I am running code in debug I am seeing below error,
The ChainedTokenCredential failed to retrieve a token from the included credentials.
ManagedIdentityCredential authentication unavailable. No Managed Identity endpoint found.
Please run 'az login' to set up account
Where I need to do az login? Thanks.

Execute az logout first and try again az login and I suggest to set default subscription by executing az account set -s "Subscription ID"

Related

Unable to revoke admin consent for added permissions: Powershell

I have one Azure Ad app where I added permissions using Add-AzADAppPermission
To grant admin consent to these, I used CLI commands here
az login
az ad app permission admin-consent --id <application-id>
I can see admin consent is granted for these permissions in Portal:
But I want to remove this consent now from PowerShell.
Is there any command like Revoke-AzADPermissionGrant to achieve that?
I can do this from Portal, but I want it from PowerShell or CLI or Graph query.
Can anyone please shed light on this?
To revoke admin_consent granted for Azure AD application permissions, you can make use of below Graph API query:
DELETE https://graph.microsoft.com/v1.0/oauth2PermissionGrants/<id>
To get the <id>, you can run this query by filtering it with Service Principal ObjectID.
GET https://graph.microsoft.com/v1.0/oauth2PermissionGrants/?$filter=clientId eq 'SP ObjectID'
I tried to reproduce the same in my environment and got the below results:
I created one Azure AD application and granted same API permissions like this:
You can get SP ObjectID of the above application like below:
Go to Azure Portal -> Azure AD -> Enterprise Applications -> Your App -> Overview
I ran the below query to get <id> by including filter like this:
GET https://graph.microsoft.com/v1.0/oauth2PermissionGrants/?$filter=clientId eq 'SP ObjectID'
Response:
I ran the DELETE query like below, I got the response successfully:
DELETE https://graph.microsoft.com/v1.0/oauth2PermissionGrants/<id>
Response:
When I checked Azure Portal, admin consent got revoked successfully for that application like below:
To do the same from PowerShell, try running below commands:
Connect-MgGraph
Import-Module Microsoft.Graph.Identity.SignIns
Remove-MgOauth2PermissionGrant -OAuth2PermissionGrantId $Id
Make sure to install Microsoft.Graph module before running those commands.
If not, try using below command to install that module:
Install-Module Microsoft.Graph -Scope CurrentUser

ERROR: The requested resource requires user authentication: https://dev.azure.com/my_org/my_project/_apis/git/repositories

I am logging into az cli using correct token:
echo my_pat | az devops login
But I see the following error while getting the existing repositories in a project:
az repos list --org {ado_org_url} --project {ado_project} --query '[*].name'
ERROR: The requested resource requires user authentication: https://dev.azure.com/my_org/my_project/\_apis/git/repositories
Am I missing any settings while setting up my pat? How can I get rid of this error?
You don't want to use the az devops login if you already set an AZURE_DEVOPS_EXT_PAT Environment Variable. If you not set an AZURE_DEVOPS_EXT_PAT Environment Variable set it first and do your CLI Task.
The az devops commands now enable sign-in with az login, you don't need to give a token if you've already signed in with az login interactively or with a username and password. However, you can't use az login to log in as the service principal. A PAT is required in that case.
If you still need to log in by using az devops login it requires the User Authentication. For that, you have to login using Service Principle
"user": {
"name": "***",
"type": "servicePrincipal"
}
References
How to securely login in Az CLI from a DevOps Pipeline
Fix ERROR: The requested resource requires User Authentication
MSDOC for Azure DevOps CLI sign in with a PAT

PAT Token isn't working on 2019 OnPrem Azure DevOps

I am having an issue getting my OnPrem Azure DevOps 2019 Server to allow things to authenticate to it with Personal Access Tokens (PAT). No mater what I do, I get failed to authenticate using the supplied token.
How I am creating my token:
Log into my OnPrem devops site
Go to my user profile icon in the top right, click security click personal access tokens, click new token
In Create new personal access toekn for some reasobn the organization (colleciton) I want to use is not listed, I am seeing an old XML based collection but not my new Inheritance based collection, why doesn't the newer format collection show up? My user account is an admin account, you'd think it would be here?
If I create a PAT token for the old XML based collection and give it full access plus a 90 day expiration it creates it fine
Now I have a PAT token bases off the old XML based collection, but that still doesn't work, if I run the AZ CLI I get this
AZ DEVOPS LOGIN --organization https://tfs.mydomain.com/OldXmlCollection --verbose
Token: {paste in token}
Creating connection with personal access token.
Failed to authenticate using the supplied token.
Command ran in 6.385 seconds (init: 0.167, invoke 6.12)
I also have the same problem if I try to set up a build agent using a PAT token. Fails every time, but if I change to negotiate auth it works immediately.
On the IIS end the service is running on the authentication is set up to Anonymous Authentication: Enabled, ASPS.NET Impersonation: Disabled, Basic Authentication: Enabled, Digest and Forms: Disabled and Windows Authentication: Enabled
any ideas what I am doing wrong, what to look at?
PAT Token isn't working on 2019 OnPrem Azure DevOps
You could try to disable IIS Basic Authentication.
That because when IIS Basic Authentication is enabled on your windows machine, it prevents you from using personal access tokens (PATs) as an authentication mechanism.
Please check this document Enabling IIS Basic Authentication invalidates using Personal Access Tokens for some more details.
What it turned out to be is a missing ACL in the file system. The service account that is running TFS needs to have write permission to the machine keys folder at %ProgramData%\Microsoft\Crypto\RSA\MachineKeys
Why in the world is the installer not setting this permission? PAT will not work until this is set

TF400813: Azure DevOps is not authorized

az devops login --organization https://dev.azure.com/XXXX
token
able to login
AZ Login - Successfully connected to Azure
Try to run
az devops project list
TF400813: The user '1a6dbb80-5290-4fd1-a938-0ad7795dfd7a\xx.yyyy#abc.com' is not authorized to access this resource.
I have full access to this organisation,still not able to access
Here's a similar thread: TF400813: The user 'Guid\FirstName#c.com' is not authorized to access this resource
Please make sure the organization is connected to AAD and your account is one of the users in this AAD.
Also try to use a microsoft email address instead of XXXX#abc.com see if you can get authorized.

Error building AzureRM Client: Error populating Client ID from the Azure CLI: No Authorization Tokens were found

Have you encountered the error mentioned in the subject line before?, I'm intrigued by it and unable to a solution. Here are the steps I executed to create a service principal
az login
-- Gives me a device code to enter in browser
Login to az non-interactively
az account set --subscription="xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
Check correct account by
az account show
Create a SP
az ad sp create-for-rbac -n "tf-authenticator" --role contributor
Run terraform plan as like below:
[jim#rhel75 msdn]$ terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.
azurerm_resource_group.tf-rg-cluster-sql: Refreshing state... os_profile_windows_config.1060902566.enable_automatic_upgrades: "true"
Plan: 28 to add, 0 to change, 0 to destroy.
------------------------------------------------------------------------
Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.
Now, I run terraform again and I get error that No authorization token found!
[jim#rhel75 msdn]$ terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.
Error: Error refreshing state: 1 error(s) occurred:
* provider.azurerm: Error building AzureRM Client: Error populating Client ID from the Azure CLI: No Authorization Tokens were found - please re-authenticate using `az login`.
Note, I tested and same behavior exhibits on
1. CentOS 7.6
2. Ubuntu 16.04
3. Azure Pipelines Release Pipeline (Which utilizes Ubuntu 16.04 agent)
Update: I encounter a weird error when I try to create a SP. I have already my default subscription but still run the below command and receive error:
az ad sp create-for-rbac -n "tf-authenticator" --role="Contributor" --scopes="/subscriptions/xxxxxxxxxxxxxxxxxxx"
Error message:
Changing "tf-authenticator" to a valid URI of "http://tf-authenticator", which is the required format used for service principal names
Get Token request returned http error: 400 and server response: {"error":"unauthorized_client","error_description":"AADSTS700016: Application with identifier 'bd58677d-d0a4-46a5-9b5a-02c6662ae149' was not found in the directory '055b56f0-423b-4b1a-b6bc-6ae09ab61485'. 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: cc58c97b-2247-4bf7-ab6c-7d1b993f0b00\r\nCorrelation ID: 42540a48-7d44-494b-9dc2-a8dd9d6c10b7\r\nTimestamp: 2019-03-14 00:46:49Z","error_codes":[700016],"timestamp":"2019-03-14 00:46:49Z","trace_id":"cc58c97b-2247-4bf7-ab6c-7d1b993f0b00","correlation_id":"42540a48-7d44-494b-9dc2-a8dd9d6c10b7","error_uri":"https://login.microsoftonline.com/error?code=700016"}
I have further drilled down that this has to do something with azure tokens, as I can create a VM instances with Azure CLI itself, please see evidence below:
az vm create --resource-group "myResourceGroup" --name "myVM" --image "Win2016Datacenter" --admin-username "Demouser" --admin-password "Demouser#123" --use-unmanaged-disk --location "Australia Southeast"
Azure Error: InvalidTemplateDeployment
Message: The template deployment failed with error: 'The resource with id: '/subscriptions/11855b5b-484f-4104-b77b-a73eb8cd74dc/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM' failed validation with message: 'The requested size for resource '/subscriptions/11855b5b-484f-4104-b77b-a73eb8cd74dc/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM' is currently not available in location 'australiasoutheast' zones '' for subscription '11855b5b-484f-4104-b77b-a73eb8cd74dc'. Please try another size or deploy to a different location or zones. See https://aka.ms/azureskunotavailable for details.'.'.
It did not launched a VM but at least its clear that it was able to proceed should size would have been right.
Can you please try to follow this documentation - https://learn.microsoft.com/en-us/azure/developer/terraform/get-started-cloud-shell-bash?tabs=bash
You need to create environment variables in order to deploy azure portal
One more thing - you need to have environment variables in .tf file
I would suggest you to not store the secrets in plain text
If you are using azure devops pipeline to deploy you can store it in the keyvault or in variables
If you are using terraform cloud with workspaces you can store it in variables