acquiretokenasync无法在网络应用中使用

时间:2017-01-13 04:57:14

标签: azure azure-active-directory

我正在尝试使用以下重载: authContext.AcquireTokenAsync(,)

这适用于简单的控制台应用程序,我可以检索令牌。 但是当我从Web应用程序运行它时,调用没有返回,也没有抛出异常。我检查了小提琴手,看来连接在这次通话中关闭了。

如何解决这个问题?它与具有受限权限的HttpContext有关吗?

3 个答案:

答案 0 :(得分:1)

可能是因为异步/等待,对于我的代码,我刚刚在graphClient.Users[FromUserEmail].SendMail(message, true)之前添加了等待。

这有效:

var sendmail = graphClient.Users[FromUserEmail].SendMail(message, true);
Task.Run(async () =>
{
    try
    {
        await sendmail.Request().PostAsync();
    }
    catch (Exception ex)
    {
        throw ex;
    }
}).Wait();

答案 1 :(得分:0)

通常,我们会在Web应用程序中使用授权代码授予流程获取令牌。为实现这一目标,我们需要实施OnAuthorizationCodeReceived事件,如下所示(full code sample):

private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
{
        var code = context.Code;

        ClientCredential credential = new ClientCredential(clientId, appKey);
        string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
        AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));

        // If you create the redirectUri this way, it will contain a trailing slash.  
        // Make sure you've registered the same exact Uri in the Azure Portal (including the slash).
        Uri uri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));

        AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, uri, credential, graphResourceId);
}

如果您要实施客户端凭据流,可以参考以下代码:

 string authority = "https://login.microsoftonline.com/{tenantId}";
 string clientId = "{clientId}";
 string secret = "{secret}";
 string resource = "https://graph.windows.net";

 var credential = new ClientCredential(clientId, secret);
 AuthenticationContext authContext = new AuthenticationContext(authority);

 var token = authContext.AcquireTokenAsync(resource, credential).Result.AccessToken;

如果您仍然遇到问题,分享详细代码会很有帮助。

答案 2 :(得分:0)

它只是开发人员对asyn / await

所犯的常见错误

您只需将 async Task<> 添加到您的方法中,当然还有接近调用令牌的方法调用的await关键字