【问题标题】:acquiretokenasync not working in a web appacquiretokenasync 在 Web 应用程序中不起作用
【发布时间】:2020-07-04 17:49:48
【问题描述】:

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

这适用于简单的控制台应用程序,我能够检索令牌。 但是当我从 Web 应用程序运行它时,调用不会返回,也不会引发异常。我签入了提琴手,似乎连接在这次通话中关闭了。

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

【问题讨论】:

    标签: azure azure-active-directory


    【解决方案1】:

    这可能是因为 async/await,对于我的代码,我刚刚在 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();
    

    【讨论】:

      【解决方案2】:

      通常,我们在 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;
      

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

      【讨论】:

      • 我尝试使用带有 AcquireToken 而不是 AcquireTokenAsync 的 2.19 版本的 Microsoft.IdentityModel.Clients.ActiveDirectory。它似乎工作。可能是什么原因?
      • 您可以分享您正在开发的详细代码。如果你正在开发一个异步方法,我们需要确保代码等待异步方法得到结果。
      【解决方案3】:

      这只是开发人员在 asyn/await 方面犯的常见错误

      您只需将 async Task 添加到您的方法中,当然还有在检索令牌的方法调用附近的 await 关键字

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-31
        • 2020-12-29
        • 2013-04-10
        • 1970-01-01
        • 1970-01-01
        • 2011-07-27
        相关资源
        最近更新 更多