为什么我的 GraphServiceClient 在每次 API 调用时都重新进行身份验证?
Why is my GraphServiceClient reauthenticating at every API call?
我正在使用 Microsoft Graph API 调用一些端点。我正在使用 C# 的 SDK。
打开提琴手跟踪时,我发现我的 _graphClientService 正在发出身份验证以在每次调用时获取新令牌。为什么会发生这种情况以及如何预防?
在某些调用中也会导致此错误。
AADSTS50196: The server terminated an operation because it encountered a client request loop
如果您正在使用 MSAL.NET
,您可以缓存令牌。 Public 客户端应用程序(desktop/mobile 应用程序)应先尝试从缓存中获取令牌,然后再通过其他方法获取令牌。
机密客户端应用程序的获取方法自行管理缓存。
资源:
看起来这段代码有效。它生成一个 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;
}
我正在使用 Microsoft Graph API 调用一些端点。我正在使用 C# 的 SDK。
打开提琴手跟踪时,我发现我的 _graphClientService 正在发出身份验证以在每次调用时获取新令牌。为什么会发生这种情况以及如何预防?
在某些调用中也会导致此错误。
AADSTS50196: The server terminated an operation because it encountered a client request loop
如果您正在使用 MSAL.NET
,您可以缓存令牌。 Public 客户端应用程序(desktop/mobile 应用程序)应先尝试从缓存中获取令牌,然后再通过其他方法获取令牌。
机密客户端应用程序的获取方法自行管理缓存。
资源:
看起来这段代码有效。它生成一个 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;
}