【问题标题】:Why is my GraphServiceClient reauthenticating at every API call?为什么我的 GraphServiceClient 在每次 API 调用时都要重新进行身份验证?
【发布时间】:2021-09-25 19:45:20
【问题描述】:

我正在使用 Microsoft Graph API 来调用一些端点。我正在使用适用于 C# 的 SDK。 打开提琴手跟踪时,我发现我的 _graphClientService 正在发出身份验证以在每次调用时获取新令牌。为什么会发生这种情况以及如何预防?

在某些调用中也会导致此错误。

AADSTS50196: The server terminated an operation because it encountered a client request loop

【问题讨论】:

  • 您使用的是什么版本的 Microsoft Graph SDK?您目前使用什么进行身份验证?代码会很有帮助。

标签: sdk microsoft-graph-api microsoft-graph-sdks


【解决方案1】:

如果您使用MSAL.NET,您可以缓存一个令牌。公共客户端应用程序(桌面/移动应用程序)应在通过其他方法获取令牌之前尝试从缓存中获取令牌。

机密客户端应用程序上的获取方法自行管理缓存。

资源:

Token cache serialization in MSAL.NET

【讨论】:

  • 这对我没有帮助。实际上,它缓存了令牌,但它不返回我用来调用 API 端点的 GraphServiceClient。相反,它以字符串形式返回令牌,我需要使用该令牌来构建 HTTP 客户端并使用 HTTP 客户端调用 API,这是我想要避免的。还有其他线索吗?
【解决方案2】:

看起来这段代码有效。它会生成一个 GraphServiceClient,在每次调用时重用相同的令牌,而不是生成一个新令牌。

 public GraphServiceClient GenerateGraphUserClient()
    {
        string userToken = GetUserAccessToken();
        GraphServiceClient client= new GraphServiceClient("https://graph.microsoft.com/v1.0", new DelegateAuthenticationProvider(async (requestMessage) =>
        {
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", userToken);
        }));
        return client;
    }

public string GetUserAccessToken()
    {
        string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
        IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
        .Create(_clientId)
        .WithTenantId(_domain)
        .Build();
        var securePassword = new SecureString();
        foreach (char c in _password)
            securePassword.AppendChar(c);
        var result = publicClientApplication.AcquireTokenByUsernamePassword(scopes, _userName, securePassword).ExecuteAsync().Result;
        return result.AccessToken;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-01
    • 1970-01-01
    • 2015-03-05
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    相关资源
    最近更新 更多