skip to Main Content

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

Answers


  1. Login with the credentials like 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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search