How can i obtain an access token from Graph explorer using C#?

50 views Asked by At

I am trying to obtain an access token from graph explorer using the following code:

string clientId = "YOUR_CLIENT_ID";
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
string tenantId = "YOUR_TENANT_ID";

IConfidentialClientApplication app = 
    ConfidentialClientApplicationBuilder.Create(clientId)
        .WithClientSecret("YOUR_CLIENT_SECRET")
        .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
        .Build();

AuthenticationResult result = await app.AcquireTokenForClient(scopes)
        .ExecuteAsync();

string accessToken = result.AccessToken;
Console.WriteLine($"Access token: {accessToken}");

The issue is that the accessToken here is shorter than what I get when I login to Graph explorer. Also the scope is set to https://graph.microsoft.com/.default, but I want to be able to send messages to teams, so I need to add the scopes Team.ReadBasic.All Channel.ReadBasic.All ChannelMessage.Send Chat.ReadWrite.

How can I do this using C#?

1

There are 1 answers

2
Qiang Fu On

AcquireTokenForClient means you are using client credential flow. According this document https://learn.microsoft.com/en-us/entra/msal/dotnet/acquiring-tokens/web-apps-apis/client-credential-flows#scopes-to-request

The scope to request for a client credential flow is the name of the resource followed by /.default. This notation tells Microsoft Entra ID to use application level permissions declared statically during the application registration.

Unlike other flows, you cannot specify scopes in the request in client credential flow. You have to use https://graph.microsoft.com/.default and configure other scopes in the Azure app registration like below:
enter image description here