无法通过AccessToken和ClientCredentialProvider创建GraphServiceClient,从而无法使用Graph API(C#控制台)发送电子邮件 [英] Unable to send Email using Graph API (C# Console) by creating GraphServiceClient through AccessToken as well as ClientCredentialProvider

本文介绍了无法通过AccessToken和ClientCredentialProvider创建GraphServiceClient,从而无法使用Graph API(C#控制台)发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误代码:OrganizationFromTenantGuidNotFound消息:承租人guid'tenantId'的承租人不存在.

我创建了一个.Net Core控制台应用程序,以使用以下2个功能发送电子邮件

我使用了以下命名空间

 使用Microsoft.Graph;使用Microsoft.Graph.Auth;//在.Net Core中,这仅在预览中使用Microsoft.Identity.Client;使用Microsoft.IdentityModel.Clients.ActiveDirectory; 

将在两个功能中发送的公用电子邮件消息

  var message =新消息{主题=吃午饭?",正文=新的ItemBody{ContentType = BodyType.Html,内容=新的自助餐厅开放."},ToRecipients = new List< Recipient>(){新收件人{EmailAddress =新的EmailAddress{地址=我的电子邮件ID"}}},CcRecipients =新列表< Recipient>(){新收件人{EmailAddress =新的EmailAddress{地址=第二个电子邮件ID"}}}}; 

以下功能所需的范围字符串[]范围=新字符串[] {"https://graph.microsoft.com/.default"};

第一种方法

  var secretClient = ConfidentialClientApplicationBuilder.Create(客户编号).WithClientSecret(clientSecret).WithAuthority(新的Uri($" https://login.microsoftonline.com/{tenantId}/v2.0")).建造();//检索Microsoft Graph的访问令牌(如果需要,获取新令牌).var authResult =等待机密客户.AcquireTokenForClient(范围).ExecuteAsync().ConfigureAwait(false);var令牌= authResult.AccessToken;//构建Microsoft Graph客户端.作为身份验证提供者,设置一个异步lambda//使用MSAL客户端获取对Microsoft Graph的仅应用访问令牌,//,并将此访问令牌插入每个API请求的Authorization标头中.GraphServiceClient graphServiceClient =new GraphServiceClient(new DelegateAuthenticationProvider(async(requestMessage)=>{//在API请求的Authorization标头中添加访问令牌.requestMessage.Headers.Authorization =新的AuthenticationHeaderValue("Bearer",令牌);}));尝试{等待graphServiceClient.Users [我的用户guid"].SendMail(message,false).要求().PostAsync();//我也尝试过等待graphServiceClient.Me.SendMail(message,false).要求().PostAsync();}抓住(前例外){} 

第二种方法

  IConfidentialClientApplication ConfidentialClientApplication = ConfidentialClientApplicationBuilder.Create(客户编号).WithTenantId(tenantId).WithClientSecret(clientSecret).建造();var authResultDirect =等待waitingclientClientApplication.AcquireTokenForClient(作用域).ExecuteAsync().ConfigureAwait(false);//需要Microsoft.Graph.Auth才能使以下各项正常工作ClientCredentialProvider authProvider =新的ClientCredentialProvider(confidentialClientApplication);GraphServiceClient graphClient = new GraphServiceClient(authProvider);尝试{等待graphClient.Users [我的用户ID"].SendMail(message,false).要求().PostAsync();//我也尝试了以下等待graphClient.Me.SendMail(message,false).要求().PostAsync();}抓住(前例外){} 

我已授予所有必需的权限.一些权限是额外的,可能不是必需的.我授予了权限,以检查这些权限是否是我收到错误但没有任何更改的原因.

我还检查了我在jwt.io上获得的令牌.我要担任以下角色

 角色":["Mail.ReadWrite","User.ReadWrite.All","Mail.ReadBasic.All","User.Read.All","Mail.Read",邮件发送","Mail.ReadBasic";], 

我看不到代码或授予的权限有任何问题,但是我仍然缺少一些我无法弄清的东西.我之所以这样说,是因为当我尝试通过调用api获取用户信息时-

2.

3.

I get the following error Code: OrganizationFromTenantGuidNotFound Message: The tenant for tenant guid 'tenantId' does not exist.

I created a .Net Core console app to send emails using the following 2 functions

I used the following namespaces

using Microsoft.Graph;
using Microsoft.Graph.Auth; //In .Net Core this is in preview only
using Microsoft.Identity.Client;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

Common Email Message to be sent in both the functions

            var message = new Message
            {
                Subject = "Meet for lunch?",
                Body = new ItemBody
                {
                    ContentType = BodyType.Html,
                    Content = "The new cafeteria is open."
                },
                ToRecipients = new List<Recipient>()
            {
                new Recipient
                {
                    EmailAddress = new EmailAddress
                    {
                        Address = "my email id"
                    }
                }
            },
                CcRecipients = new List<Recipient>()
             {
                 new Recipient
                 {
                     EmailAddress = new EmailAddress
                     {
                         Address = "2nd email id"
                     }
                 }
             }
            };

Scope required in the following functions string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

1st Method

var confidentialClient = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithClientSecret(clientSecret)
                .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}/v2.0"))
                .Build();

            // Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
            var authResult = await confidentialClient
                    .AcquireTokenForClient(scopes)
                    .ExecuteAsync().ConfigureAwait(false);

            var token = authResult.AccessToken;
            // Build the Microsoft Graph client. As the authentication provider, set an async lambda
            // which uses the MSAL client to obtain an app-only access token to Microsoft Graph,
            // and inserts this access token in the Authorization header of each API request. 
            GraphServiceClient graphServiceClient =
                new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
                {
                    // Add the access token in the Authorization header of the API request.
                    requestMessage.Headers.Authorization =
                            new AuthenticationHeaderValue("Bearer", token);
                })
                );

try
            {
                await graphServiceClient.Users["my user guid"]
                      .SendMail(message, false)
                      .Request()
                      .PostAsync();

//I also tried with 
               await graphServiceClient.Me
                      .SendMail(message, false)
                      .Request()
                      .PostAsync();
            }
            catch (Exception ex)
            {


            }

            

2nd Method

 IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
            .Create(clientId)
            .WithTenantId(tenantId)
            .WithClientSecret(clientSecret)
            .Build();

            var authResultDirect = await confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync().ConfigureAwait(false);

//Microsoft.Graph.Auth is required for the following to work
            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
            GraphServiceClient graphClient = new GraphServiceClient(authProvider);


            try
            {
                await graphClient.Users["my user id"]
                        .SendMail(message, false)
                        .Request()
                        .PostAsync();

//I also tried the following
                   await graphClient.Me
                        .SendMail(message, false)
                        .Request()
                        .PostAsync();
            }
            catch (Exception ex)
            {

                
            }

I have given all the required permissions. Some of the permissions are extra and may not be required. I gave the permissions to check if those permissions are the reason why I am getting the error but nothing changed.

I have also checked the token I am getting on jwt.io. I am getting the following roles

 "roles": [
     "Mail.ReadWrite",
     "User.ReadWrite.All",
     "Mail.ReadBasic.All",
     "User.Read.All",
     "Mail.Read",
     "Mail.Send",
     "Mail.ReadBasic"
  ],

I don't see any issue with the code or with the permissions that I have given but I am still missing something which I am unable to figure out. The reason why I say this is because when I tried to get user information by calling the api - https://graph.microsoft.com/v1.0/users, I get the users information as below.

value = [
{
    "businessPhones": [],
    "displayName": "user display name",
    "givenName": "user first name",
    "jobTitle": null,
    "mail": null,
    "mobilePhone": null,
    "officeLocation": null,
    "preferredLanguage": "en",
    "surname": "user last name",
    "userPrincipalName": "user information",
    "id": "user id"
    }
  ]

Any help is appreciated

解决方案

This is because your Azure AD tenant does not have an Exchange online license under the O365 subscription. As a result, your tenant does not have the ability to send Email messages.

If you have an o365 subscription, you'll see it here.

1.

2.

3.

这篇关于无法通过AccessToken和ClientCredentialProvider创建GraphServiceClient,从而无法使用Graph API(C#控制台)发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆