【发布时间】:2020-11-05 16:32:45
【问题描述】:
我按照以下步骤操作:
- 我在 Azure 中创建了一个应用注册。
- 进入证书和机密并创建新的客户端机密。
- 在 API 权限中,授予所有 Mail.* 权限名称的 Delegated 权限。
- 然后我点击了
Grant admin consent for {my org}。
在我的代码(.net 核心控制台应用程序)中,我编写了以下内容:
var clientId = "23fff856-***";
var tenantId = "6f541345-***";
var clientSecret = "_Sir**(";
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantId)
.WithClientSecret(clientSecret)
.Build();
var authProvider = new ClientCredentialProvider(confidentialClientApplication);
var graphClient = new GraphServiceClient(authProvider);
var message = new Message
{
Subject = "my subject",
Body = new ItemBody {ContentType = BodyType.Text, Content = "body"},
ToRecipients = new List<Recipient>
{
new Recipient
{
EmailAddress = new EmailAddress{Address = "foo@gmail.com"}
}
}
};
await GraphClient.Me
.SendMail(message, true)
.Request()
.PostAsync();
这会导致错误:
"code":"NoPermissionsInAccessToken",
"message":"The token contains no permissions, or permissions can not be understood."
我已授予所有权限。我错过了什么?
【问题讨论】:
-
由于您使用的是客户端凭据流,因此您需要在 Azure 门户上使用应用程序权限。请添加 Mail.Send Application 权限,它将起作用。
-
@Shiva-MSFTIdentity 我刚刚完成并收到以下错误:
Code: BadRequest Message: Current authenticated context is not valid for this request. This occurs when a request is made to an endpoint that requires user sign-in. For example, /me requires a signed-in user. Acquire a token on behalf of a user to make requests to these endpoints. Use the OAuth 2.0 authorization code flow for mobile and native apps and the OAuth 2.0 implicit flow for single-page web apps. -
删除“我”并添加用户[“用户id”],因为“我”谈论的是登录用户,我们这里没有任何用户。
-
@Shiva-MSFTIdentity 谢谢。当您说 UserId 时?您是指 Azure 中的 UserId 吗?如果是这样,我如何找到用户 ID?
-
是的,它是 Azure AD 中的用户对象 ID。您还可以使用 userPrincipalname 进行测试。您可以使用 /users endpoint 获取用户的用户 ID,并使用 displayname 或 userPrincipalname 进行过滤。 :)-
标签: c# azure microsoft-graph-api microsoft-graph-sdks microsoft-graph-mail