Avinash
Avinash

Reputation: 2183

Not able retrieve Azure graph token from global.asax

I am on working on MVC application and I am able to fetch the graph token from controller but same code(PFB code) is not working in Global.asax.cs

It is not giving any error but it is paused at authContext.AcquireTokenAsync and it is not moving forward.

protected void Session_Start(Object sender, EventArgs e)
        {
            string tenantId = "TenantId";
            string clientId = "CleintId";
            string clientSecret = "ClientSecret";
            AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/" + tenantId);
            ClientCredential credential = new ClientCredential(clientId, clientSecret);
            AuthenticationResult result = await authContext.AcquireTokenAsync("https://graph.microsoft.com", credential);
            return result.AccessToken;
        }

Could any one please help me here.

🎉

Upvotes: 2

Views: 264

Answers (1)

Joey Cai
Joey Cai

Reputation: 20127

Because the await authContext.AcquireTokenAsync is a asynchronous method, so it will wait and not move forward until it is finish.

Use the code as below in Global.asax.cs:

protected async void Session_Start(Object sender, EventArgs e)
{
    string tenantId = "xxxxxxxxxxxxxxxxxxxxxx";
    string clientId = "xxxxxxxxxxxxxxxxxxxxxx";
    string clientSecret = "xxxxxxxxxxxxxxxxxxxxxx";
    AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/" + tenantId);
    ClientCredential credential = new ClientCredential(clientId, clientSecret);
    AuthenticationResult result =authContext.AcquireTokenAsync("https://graph.microsoft.com", credential);
    var accesstoken = result.AccessToken;
}

enter image description here

Upvotes: 2

Related Questions