Username/Password Azure authentication without ClientID

168 Views Asked by At

Via Azure command line I can login using my personal Entra ID account and generate a MS Graph token using something like this

az login -u [email protected] -p mypassword --tenant mytenantid
az account get-access-token --resource-type ms-graph

I'm trying to do the same via C# application, but I can't figure out which one of the countless authentication classes I should use.

The easiest one seemed to be the UsernamePasswordCredential, but it has a mandatory clientID parameter that I don't know how to set, since I'm not using any client ID in my az command line.

There would also be an AzureCliCredential class but its options don't seem to include any username nor password parameters.

2

There are 2 best solutions below

0
Gaurav Mantri On BEST ANSWER

You would always need a client id for logging in (including Azure CLI, PowerShell or Portal).

In case of Azure CLI (which is also an application like any other Azure AD application), the client id is 04b07795-8ddb-461a-bbee-02f9e1bf7b46.

When you login using az login -u [email protected] -p mypassword --tenant mytenantid, Azure CLI automatically makes use of above mentioned client id.

enter image description here

Please see the list of all Microsoft application ids here: https://learn.microsoft.com/en-us/troubleshoot/azure/active-directory/verify-first-party-apps-sign-in#application-ids-of-commonly-used-microsoft-applications.

5
Rukmini On

Note that: Azure CLI uses its own ClientID but it is mandatory to pass ClientID if you want to use UsernamePasswordCredential to generate access token.

If you don't want to pass the ClientID while generating the access token, then make use of DefaultAzureCredential as a wokkaround like below:

Login with the credentials as below:

az login -u [email protected] -p mypassword --tenant mytenantid

enter image description here

Now to generate the access token without passing the ClientID, make use of below code:

using Azure.Core;
using Azure.Identity;

// Define the resource ID for the Azure AD application you want to access.
string resourceId = "https://graph.microsoft.com";

var tokenCredential = new DefaultAzureCredential();

var accessToken = await tokenCredential.GetTokenAsync(
    new TokenRequestContext(scopes: new string[] { resourceId + "/.default" })
);

Console.WriteLine(accessToken.Token);

Access token is generated successfully:

enter image description here