我正在开发MVC应用程序,并且能够从控制器中获取图形令牌,但是相同的代码(PFB代码)在Global.asax.cs中不起作用
它没有给出任何错误,但是它在 authContext.AcquireTokenAsync 处暂停了,并且没有前进。
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;
}
有人可以在这里帮助我吗?
?
答案 0 :(得分:1)
由于await authContext.AcquireTokenAsync
是一种异步方法,因此它将等待,直到完成为止。
使用以下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;
}