【发布时间】:2023-03-21 08:55:01
【问题描述】:
我正在尝试使用 Graph API 获取当前用户的数据。我想获取访问令牌并将其附加到请求消息中。所以我想跳过登录用户界面。某些原因我收到 (401) Unauthorized 错误,无效用户...我从那里注册了我的 app(mvc) AAD,以及密钥、客户端 ID、租户 ID。
这是获取token的方法:
public static string GetToken()
{
string authority = "https://graph.microsoft.com/{tenantID}/oauth2/token";
string clientId = "client id";
string secret = "client secret";
string resource = "https://graph.microsoft.com";
AuthenticationContext authContext = new AuthenticationContext(authority);
ClientCredential clientCredential = new ClientCredential(clientId, secret);
AuthenticationResult authResult = authContext.AcquireToken(resource, clientCredential);
return authResult.AccessToken;
}
这是代码,我在其中附加了访问令牌:
public static GraphServiceClient GetAuthenticatedClient()
{
GraphServiceClient graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
string accessToken = GetToken();
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}));
return graphClient;
}
任何建议都会有所帮助,因为我不知道。
【问题讨论】:
标签: azure-active-directory access-token microsoft-graph-api azure-ad-graph-api