Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inviting a User in Azure AD through Microsoft Graph API doesn't work

Below is the code that I have put to invite a user in Azure AD.

I get an "unauthorized" response. I am not sure what permission/setting are missing. Do anyone have the idea.

string accessToken = await AuthenticationHelper.GetTokenForApplication ();
InvitationModel invite = new InvitationModel ();
invite.invitedUserEmailAddress = user.Email;
invite.inviteRedirectUrl = ConfigurationManager.AppSettings["InviteRedirectUrl"];
invite.sendInvitationMessage = true;
using (HttpClient client = new HttpClient ()) {
    client.BaseAddress = new Uri ("https://graph.microsoft.com");

    client.DefaultRequestHeaders.Accept.Add (
        new MediaTypeWithQualityHeaderValue ("application/json"));

    client.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue ("Bearer", accessToken);

    HttpResponseMessage response =
        client.PostAsJsonAsync<InvitationModel> ("v1.6/invitations", invite).Result;

    dynamic inviteResult =
        response.Content.ReadAsAsync<dynamic> ().Result;

    if (inviteResult.status != "Error") { }
}

1 Answers

You're problem is that you conflating Microsoft Graph and Azure AD Graph here. These are two distinct APIs with different calling conversions and permission scopes.

In order to create an Invitation you will need one of the following permission scopes (Note that the first is the most restrictive permission (globally), the last the most permissive):

  • User.Invite.All
  • User.ReadWrite.All
  • Directory.ReadWrite.All

Note that all of these scopes are admin-restricted and will require Admin Consent before you can use them

Once you have a valid token, you'll need to make a POSTcall to https://graph.microsoft.com/v1.0/invitations with the following body:

{
  "invitedUserEmailAddress": "[email protected]",
  "inviteRedirectUrl": "https://myapp.com"
}

Since you're using C#, I would strongly recommend using Microsoft Graph Client Library rather than hand-rolling your own HttpClient calls.

like image 160
Marc LaFleur Avatar answered Oct 29 '25 05:10

Marc LaFleur