本文介绍了“租户guid的租户不存在"使用GraphAPI时-即使用户类型为Member的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是获取电子邮件的代码

  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(); 

这是获取访问令牌的代码

 私有常量字符串_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;私有常量字符串_grantType ="client_credentials";私有常量字符串_scope ="https://graph.microsoft.com/.default";公共异步Task< string>GetAccessTokenAsync(){var content = new FormUrlEncodedContent(new []{新的KeyValuePair< string,string>("Grant_Type",_grantType),新的KeyValuePair< string,string>("Scope",_scope),新的KeyValuePair< string,string>("Client_Id",_clientId),新的KeyValuePair< string,string>("Client_Secret",_ clientSecret)});var responce =等待_httpClient.PostAsync(_uri,content);responce.EnsureSuccessStatusCode();var jsonString =等待responce.Content.ReadAsStringAsync();var document =等待JsonDocument.ParseAsync(jsonString.ToStream());返回document.RootElement.GetProperty("access_token").GetString();} 

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

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

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

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

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

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

      var privacyClientApplication = ConfidentialClientApplicationBuilder.创建(configuration.ClientId).WithTenantId(configuration.TenantId).WithClientSecret(configuration.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.

    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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 01:39