Get bearier token for Azure Graph api

Copper Contributor

I found 3 ways:

1.  from MSDN example:   result = await app.AcquireTokenForClient(scopes)

active-directory-dotnetcore-daemon-v2/Program.cs at master · Azure-Samples/active-directory-dotnetco...

2. 

// https://docs.microsoft.com/en-us/graph/auth-v2-service

 

private static async Task<AccessToken> WebRequestTokenBearer(string tenantId, string appId, string client_secret)
{
string url = "https://login.microsoftonline.com/"+ tenantId + "/oauth2/v2.0/token";

var values = new Dictionary<string, string>
{
{ "client_id", appId },
{ "scope", "https://graph.microsoft.com/.default" },
{ "client_secret", client_secret },
{ "grant_type", "client_credentials" }
};
var data = new FormUrlEncodedContent(values);

using var client = new HttpClient();
var response = await client.PostAsync(url, data);
string jsonToken = response.Content.ReadAsStringAsync().Result;

AccessToken result = JsonConvert.DeserializeObject<AccessToken>(jsonToken);

return result;
}

 

3. Once call Graph API method  using delegation permission its possible to retrieve token from  

 

GraphServiceClient graphClient = new GraphServiceClient(GetDelegatedAuthProvider());
var request = graphClient.Me.Request();
HttpRequestMessage httpRequest = request.GetHttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
var response = await request.Client.HttpProvider.SendAsync(httpRequest);
string token = response.RequestMessage.Headers.Authorization.Parameter;

 

Method 1,2 giving the same length but different hash but third a way bigger and require to apply Azure Login popup dialog.  Which one is correct?

1 Reply

@ktchoumak 

 

I do not understand why Microsoft using such low informative way in it's snippets?

Client credential flows · AzureAD/microsoft-authentication-library-for-dotnet Wiki (github.com)

 

Here is main wrapper:

        private static async Task<AuthenticationResult> GetToken(string tenantId, string appId, string clientSecret)
        {
            // this object will cache tokens in-memory - keep it as a singleton
            var singletonApp = ConfidentialClientApplicationBuilder.Create(appId)
                .WithClientSecret(clientSecret)
                .Build();

            // If instead you need to re-create the ConfidentialClientApplication on each request, you MUST customize 
            // the cache serialization (see below)

            // when making the request, specify the tenanted authority
            // uses the token cache automatically, which is optimized for multi-tenant access
            var authResult = await singletonApp.AcquireTokenForClient(scopes: new[] { "https://graph.microsoft.com/.default" })
                .WithAuthority(AzureCloudInstance.AzurePublic, tenantId)  // do not use "common" or "organizations"!
                .ExecuteAsync();

            return authResult;
        }