“租户 guid 的租户不存在"使用 GraphAPI 时 - 即使用户类型为 Member

quot;The tenant for tenant guid does not existquot; when using GraphAPI - Even with user type as Member(“租户 guid 的租户不存在使用 GraphAPI 时 - 即使用户类型为 Member)
本文介绍了“租户 guid 的租户不存在"使用 GraphAPI 时 - 即使用户类型为 Member的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Microsoft Graph API 访问电子邮件.当我尝试访问电子邮件时,出现以下错误.

<块引用>

Microsoft.Graph.ServiceException: '代码:OrganizationFromTenantGuidNotFound

消息:租户 guid '<some id>' 的租户不存在.

这是获取电子邮件的代码

var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) =>{requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);返回Task.CompletedTask;}));var userId = "quicksilverconnect@outlook.com";//也试过 vijaynirmal@quicksilverconnectoutlook.onmicrosoft.comvar messageId = "实际消息 ID";var email = await graphServiceClient.Users[userId].Messages[messageId].Request().GetAsync();

这是获取访问令牌的代码

private const string _clientId = "xxxxxxx-xxxxxx-xxxxxxx-xxxx";私有常量字符串_clientSecret =xxxxxxx-xxxxxx-xxxxxxx-xxxx";私有常量字符串_tenantName =ecd90453-34b6-xxxx-xxxx-xxxxxxxxx";私有只读字符串_uri = $"https://login.microsoftonline.com/{_tenantName}/oauth2/v2.0/token";private const string _grantType = "client_credentials";private const string _scope = "https://graph.microsoft.com/.default";公共异步任务<字符串>GetAccessTokenAsync(){var content = new FormUrlEncodedContent(new[]{new KeyValuePair<string, string>(Grant_Type", _grantType),new KeyValuePair(Scope", _scope),new KeyValuePair<string, string>(Client_Id", _clientId),new KeyValuePair(Client_Secret", _clientSecret)});var response = await _httpClient.PostAsync(_uri, content);response.EnsureSuccessStatusCode();var jsonString = 等待响应.Content.ReadAsStringAsync();var 文档 = 等待 JsonDocument.ParseAsync(jsonString.ToStream());return document.RootElement.GetProperty("access_token").GetString();}

我已经在网上搜索了解决方案.我找到了一些解决方案,但没有一个对我有用.

  1. 用户类型必须是成员.我的用户类型已经是会员.原始问题 -

  2. 使用域作为tenentId.它不工作.原始问题 -

    也许您也可以在同一页面上购买 Exchange Online(例如 Exchange Online (Plan 2))以访问电子邮件.

    顺便说一句,您的代码中有一个错误.您将 client_credentials 用作Grant_Type";并使用 DelegateAuthenticationProvider.如果要使用DelegateAuthenticationProvider,需要设置Grant_Type"作为 password 而不是 client_credentials.

    要使用客户端凭据身份验证,您需要安装 Microsoft.Graph.Auth.注意:这是一个预发布包.这是一个代码片段

    var encryptedClientApplication = ConfidentialClientApplicationBuilder.Create(配置.ClientId).WithTenantId(配置.TenantId).WithClientSecret(配置.ClientSecret).建造();var authProvider = new ClientCredentialProvider(confidentialClientApplication);var graphServiceClient = new GraphServiceClient(_clientCredentialProviderauthProvider);

    I am trying to access email using Microsoft Graph API. When I try to access the email I got the below error.

    Microsoft.Graph.ServiceException: 'Code: OrganizationFromTenantGuidNotFound

    Message: The tenant for tenant guid '<some id>' does not exist.

    Here is the code to get the emails

    var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) =>
    {
        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
        return Task.CompletedTask;
    }));
    
    var userId = "quicksilverconnect@outlook.com"; // Tried vijaynirmal@quicksilverconnectoutlook.onmicrosoft.com also
    var messageId = "Actual message id";
    
    var email = await graphServiceClient.Users[userId].Messages[messageId].Request().GetAsync();
    

    Here is the code to get access token

    private const string _clientId = "xxxxxxx-xxxxxx-xxxxxxx-xxxx";
    private const string _clientSecret = "xxxxxxx-xxxxxx-xxxxxxx-xxxx";
    private const string _tenantName = "ecd90453-34b6-xxxx-xxxx-xxxxxxxxx";
    private readonly string _uri = $"https://login.microsoftonline.com/{_tenantName}/oauth2/v2.0/token";
    private const string _grantType = "client_credentials";
    private const string _scope = "https://graph.microsoft.com/.default";
    
    public async Task<string> GetAccessTokenAsync()
    {
        var content = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("Grant_Type", _grantType),
            new KeyValuePair<string, string>("Scope", _scope),
            new KeyValuePair<string, string>("Client_Id", _clientId),
            new KeyValuePair<string, string>("Client_Secret", _clientSecret)
        });
        var responce = await _httpClient.PostAsync(_uri, content);
    
        responce.EnsureSuccessStatusCode();
    
        var jsonString = await responce.Content.ReadAsStringAsync();
    
        var document = await JsonDocument.ParseAsync(jsonString.ToStream());
    
        return document.RootElement.GetProperty("access_token").GetString();
    }
    

    I have searched in net for solutions. I found some solutions but none of them is working for me.

    1. User Type must be a Member. My user type is already Member. Original issue - "The tenant for tenant guid does not exist" even though user is listed on users endpoint?

    2. Using Domain as tenentId. Its not working. Original issue - Getting "The tenant for tenant guid '' does not exist"

       private const string _tenantName = "quicksilverconnectoutlook.onmicrosoft.com";
      

    Some interesting observations

    • I was able to get the user but not their mails. Note: In this below code, only user id is working not their email id.

        var userId = "8685e56b-b1a8-45cf-a5d1-5c5ddadd0f3e"; 
        // EmailId (quicksilverconnect@outlook.com) is not working here
        var user = await graphServiceClient.Users[userId].Request().GetAsync();
      

    • I found out that if I use the access token generated by Graph Explorer then my code is working properly. So probably the issue is in my GetAccessTokenAsync code or its configuration details.

    Update:

    I want to use Application permissions not Delegated permissions because my application will use Notification Subscriptions to get a notification when a new mail is received by any users. Also, I want to get the full email details of the new mail. In short, this application will run in the background.

    var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) =>
    {
        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
        return Task.CompletedTask;
    }));
    
    var subscription = await graphServiceClient.Subscriptions.Request().AddAsync(new Subscription()
    {
        Resource = "/users/quicksilverconnect@outlook.com/messages",
        ChangeType = "created",
        ExpirationDateTime = DateTimeOffset.Now.AddDays(3).AddHours(-1),
        NotificationUrl = "https://asdasdasd.azurewebsites.net/Outlook/NewMailListener",
        ClientState = Guid.NewGuid().ToString()
    });
    

    解决方案

    It seems the problem was caused by you don't have O365 subscription. Although you have azure subscription and have an email for your azure account, but you do not have O365 subscription. So you can just get the users by graph but can not get email messages by graph.

    For this problem, you can just go to this page(login with you azure admin account) and buy O365 subscription.(for example: Office 65 E3)

    Maybe you can also buy Exchange online(such as Exchange Online (Plan 2)) on the same page to access the email message.

    By the way, there is a mistake in your code. You use client_credentials as "Grant_Type" and use DelegateAuthenticationProvider. If you want to use DelegateAuthenticationProvider, you need to set "Grant_Type" as password but not client_credentials.

    To use client credential authentication, You need to install Microsoft.Graph.Auth. Note: this is a prerelease package. Here is a code snippet

    var confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                .Create(configuration.ClientId)
                                                .WithTenantId(configuration.TenantId)
                                                .WithClientSecret(configuration.ClientSecret)
                                                .Build();
    var authProvider = new ClientCredentialProvider(confidentialClientApplication);
    var graphServiceClient = new GraphServiceClient(_clientCredentialProviderauthProvider);
    

    这篇关于“租户 guid 的租户不存在"使用 GraphAPI 时 - 即使用户类型为 Member的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)