microsoftgraph / microsoftgraph/msgraph-sdk-dotnet

Unable to invite external users

Open
#2,878 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Status: Needs investigation type:bug
Dominant language
C#
Stars
789
Forks
264
Avg merge
15h 17m
Merged PRs (30d)
3

Description

Describe the bug

I am trying to invite external user to sharePoint library. Only able to add with exting users (external/organizational) with their respective emails. However when tried to add new external user it says

Working fine with invitation sent from Sharepoint Portal
There is no issue when tried from Developer Graph Explorer itself
Working code

Post: https://graph.microsoft.com/v1.0/drives/b!MWXmufRKuUOoXtfXl2mrn97AHlHIfilDiYetCGFDjblVW8RXsw5ET5IGpX8VxdeB/root/invite
Request Body: {
  "recipients": [
    {
      "email": "gopal@gmail.com"
    }
  ],
  "message": "You have been invited to access the file.",
  "requireSignIn": true,
  "sendInvitationMessage": true,
  "roles": [
    "write"
  ],
  "notifyRecipients": true
}

The issue is just on "SDK" and "REST API using Http Client"

Authentication used
Using Azure authentication with Application based permission using client secret

Graph Permission Set

Image

All allowed for cross tenant settings
Image

Expected behavior

External users must be able to invited from SDK and Rest API. SharePoint portal and Developer Graph Explorer is working fine

How to reproduce

Not working code Sample

      public string DefaultScope = "https://graph.microsoft.com/.default";
       private GraphServiceClient _GraphService;
       internal GraphServiceClient Service
       {
           get
           {
               try
               {
                   if (_GraphService == null)
                   {
                       var scopes = new[] { DefaultScope };
                       var options = new TokenCredentialOptions
                       {
                           AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
                       };
                       var clientSecretCredential = new ClientSecretCredential(TenantId, ClientId, ClientSecret, options);
                       var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
                       _GraphService = graphClient;
                   }
                   return _GraphService;
               }
               catch (Exception ex)
               {
                   throw;
               }
           }
       }
//this works fine if email is AD user(organizational or External User)
//But if Email is some other user beside users in AD throws exception as above
public void InviteUser() {
   var recipients = new List<DriveRecipient>() { new DriveRecipient() { Email = "gopal@gmail.com" } };
   var diveId="b!WRqc2bfDTE2DkegjDrjE2j1bRgSiiIZJilysXZ3qHVKAyMwfK-OwRJuWBnso0xyz";
   var result = await Service.Drives[spRequest.ItemId].Root.Invite(recipients, true, new List<string>{"read""}, true, null, false).Request().PostAsync();
}

Even tried with the Rest API

private async Task<string> GetAccessTokenAsync()
{
    try
    {
        var credential = new ClientSecretCredential(TenantId, ClientId, ClientSecret);
        var tokenRequestContext = new TokenRequestContext(new[] { DefaultScope });
        var token = await credential.GetTokenAsync(tokenRequestContext);
        return token.Token;
    }
    catch(Exception ex)
    {
        throw;
    }
}

//works fine for existing users of AD
public async Task SendInviteAsync(string driveId, string email)
{
    try
    {
        using (HttpClient client = new HttpClient())
        {
            var token = await GetAccessTokenAsync();
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            var requestBody = new
            {
                recipients = new[]
                {
            new { email }
        },
                message = "You have been invited to access the file.",
                requireSignIn = true,
                sendInvitationMessage = true,
                roles = new[] { "write" },
                notifyRecipients = true
            };

            string jsonBody = Newtonsoft.Json.JsonConvert.SerializeObject(requestBody);
            HttpContent content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

            string url = $"https://graph.microsoft.com/v1.0/drives/{driveId}/root/invite";

            HttpResponseMessage response = await client.PostAsync(url, content);
            string responseContent = await response.Content.ReadAsStringAsync();

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("✅ Invitation sent successfully!");
                Console.WriteLine(responseContent);
            }
            else
            {
                Console.WriteLine($"❌ Error: {response.StatusCode}");
                Console.WriteLine(responseContent);
            }
        }
    }
    catch(Exception ex)
    {

    }
}
SDK Version

Latest

Latest version known to work for scenario above?

No response

Known Workarounds

No response

Debug output

Code: sharingFailed
Message: Please configure B2B collaboration settings correctly and troubleshoot first, "https://aka.ms/b2b-troubleshoot". Error from Entra B2B: At least one invitation failed. Error: RequestCreationFailure, message: Failed to create invitation request.
Inner error:
AdditionalData:
date: 2025-03-19T10:44:37
request-id: 16fc6f7d-bae5-4225-a6d7-dbd8f5c13ac8
client-request-id: 16fc6f7d-bae5-4225-a6d7-dbd8f5c13ac8
ClientRequestId: 16fc6f7d-bae5-4225-a6d7-dbd8f5c13ac8

Configuration

No response

Other information

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with GraphServiceClient's Drives[...].Root.Invite call and the POST to /drives/{driveId}/root/invite, comparing both with the working Graph Explorer request. Inspect the sharingFailed response and its Entra B2B RequestCreationFailure details, then reproduce an invitation for a non-directory external email and confirm the SDK and REST paths behave consistently.

Written by the indexing model from the issue text.

Assessment

Tech stack
azure, csharp
Domain
api, authentication
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.