【发布时间】:2020-06-25 22:39:03
【问题描述】:
我们在 Azure AD 中注册了一个应用程序,并设置了客户端机密以将其作为守护程序应用程序运行(无需用户交互)。我们有 API 权限 Mail.Send 和 User.Read 管理员同意 Microsoft Graph API。
我的理解是使用构造一个ConfidentialClientApplication来获取注册应用程序的访问令牌,通过它我可以创建一个GraphServiceClient。然后我可以使用客户端以用户身份发送电子邮件。
但我得到以下异常,说令牌中没有权限:(但我确实提供了获取权限的范围)
Message: The token contains no permissions, or permissions can not be understood.
Inner error:
AdditionalData:
request-id: omitted-xxxx-xxx-...31c53
date: 2020-03-13T23:41:08
ClientRequestId: omitted-xxxx-xxx-...31c57
at Microsoft.Graph.HttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
at Microsoft.Graph.BaseRequest.SendRequestAsync(Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
at Microsoft.Graph.BaseRequest.SendAsync(Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
at GraphCallsFromServiceAccount.MyGraphClient.SendEmail(GraphServiceClient graphClient) in C:\Users\xxxx\source\repos\GraphCallsFromAccount\MyGraphClient.cs:line 109
相关代码:
// create a ConfidentialClientApplication:
var app = ConfidentialClientApplicationBuilder.Create(AppClientId)
.WithAuthority(new Uri("https://login.microsoftonline.com/"+ TenantId + "/oauth2/v2.0/token"))
.WithClientSecret(ClientSecretString)
.Build();
var scopes = new string[] { "https://graph.microsoft.com/.default" }; // if changed to "Mail.Send", it throws errors saying invalid scope.
GraphServiceClient graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMg) =>
{
// add access token to header
var result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
requestMg.Headers.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken);
}));
// send email:
try
{
var toAddress = "john_doe@helloworld.com";
var SenderAddress = "jane_doe@helloworld.com";
var recipient = new Recipient()
{
EmailAddress = new EmailAddress()
{
Name = "John Doe",
Address = toAddress,
}
};
Message email = new Message
{
Body = new ItemBody
{
Content = "<b>hello world</b>",
ContentType = BodyType.Html,
},
Subject = "hello world",
ToRecipients = new List<Recipient>() { recipient },
};
Console.WriteLine("hello 2");
await graphClient.Users["john_doe@helloworld.com"].SendMail(email, false).Request().PostAsync();
}
catch (Exception ex)
{
Console.WriteLine("ex: " + ex);
}
那么我如何请求放入访问令牌中的正确权限?感谢您的帮助
【问题讨论】:
标签: email azure-active-directory microsoft-graph-api access-token