我有一个使用 MSAL 和 v2.0 端点来登录用户并获取 token 的应用。
我最近将其更改为 ADAL 和正常的 AAD 端点(还更改了应用程序),现在当我尝试使用 GraphService 时,出现以下错误:当前经过身份验证的上下文对此请求无效
- 我的用户是管理员
- 所有权限均已授予
- token 已成功检索
这是我使用的代码:
public static GraphServiceClient GetAuthenticatedClient()
{
GraphServiceClient graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
string accessToken = await SampleAuthProvider.Instance.GetUserAccessTokenAsync();
// Append the access token to the request.
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
}));
return graphClient;
}
调用该方法,实际发生错误的地方:
try
{
// Initialize the GraphServiceClient.
GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();
// Get events.
items = await eventsService.GetMyEvents(graphClient);
}
catch (ServiceException se)
{
}
获取 token :
public async Task<string> GetTokenAsync()
{
ClientCredential cc = new ClientCredential(appId, appSecret);
AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/tenant.onmicrosoft.com");
AuthenticationResult result = await authContext.AcquireTokenAsync("https://graph.microsoft.com", cc);
return result.AccessToken;
}
在网上找不到任何内容,所以我不知道如何继续。
最佳答案
此异常是由使用客户端凭据流获取的 token 引起的。在此流程中,没有我的上下文。
要解决此问题,您需要指定要获取其事件的事件。或者您需要提供委托(delegate) token 。
代码供您引用:
//var envens=await graphClient.Me.Events.Request().GetAsync();
var envens = await graphClient.Users["<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e39b9b9ba39b9b9bcd8c8d8e8a80918c908c8597cd808c8e" rel="noreferrer noopener nofollow">[email protected]</a>"].Events.Request().GetAsync();
关于error-handling - 微软图: Current authenticated context is not valid for this request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42090125/