为什么我的GraphServiceClient在每次API调用时都要重新进行身份验证? [英] Why is my GraphServiceClient reauthenticating at every API call?

查看:30
本文介绍了为什么我的GraphServiceClient在每次API调用时都要重新进行身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Microsoft Graph API调用一些终结点。我正在使用C#的SDK。 在打开fiddler跟踪时,我发现my_raphClientService在每次调用时都会发出身份验证以获取新令牌。为什么会发生这种情况,如何防止呢?

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

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

推荐答案

看起来这段代码可以工作。它生成一个GraphServiceClient,该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;
    }

这篇关于为什么我的GraphServiceClient在每次API调用时都要重新进行身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆