HowTo: invite AAD user with Microsoft Graph
By rickvdbosch
- 5 minutes read - 1043 wordsOne of the time consuming tasks we’re facing at my current assignment is inviting users to our Azure Active Directory tenant. Especially since we (used to) do this in the Azure Portal. We’re using Azure Active Directory B2B to which external users are invited as guests. We investigated using Microsoft Graph to automate this process. Since there’s several things to take into account when implementing this, here’s a quick HowTo.
By the way, I’ll be taking some shortcuts here and there. For instance in creating Views and Controller actions for the web app. I will do so because I want this guide to focus on how to call the Microsoft Graph. And because I’m assuming you know how to create a View or Controller action.
What will we create?
We’ll create a Web App that uses application credentials to invite users to an Azure Active Directory tenant using Microsoft Graph. We’re using application credentials because we want to enable this functionality for different types of users. They might not all have admin rights on the tenant. This way the application is granted the right to invite users so the user doesn’t have to be. To keep the guide somewhat simple and focused on the task at hand, I’m ignoring login in to the web app for now.
Azure Active Directory endpoints
There are currently two Azure Active Directory endpoints: V1 and V2. The V1 endpoint is the endpoint we know. V2 has some extra functionality. Here’s the biggest difference:
The v2.0 endpoint allows developers to write apps that accept sign-in from both Microsoft Accounts and Azure AD accounts, using a single auth endpoint. This gives you the ability to write your app completely account-agnostic; it can be ignorant of the type of account that the user signs in with. Of course, you can make your app aware of the type of account being used in a particular session, but you don’t have to.
Source: What’s different about the v2.0 endpoint?
Next to this, app registrations for the V2 endpoint are not done in the Azure Portal, but in the separate Application Registration Portal. For this HowTo we will use the Azure Active Directory V1 endpoint and an app registration in the Azure Portal.
The guide
These are the steps needed to create this simple sample application.
1. Create an App Registration in the Azure Portal
- Go to the Azure Portal and open up Azure Active Directory
- Go to App Registrations
- Click New application registration
- Give the new App Registration a Name, choose Web app/API as the Application Type and give it a (fake) Sign-on URL.
- Click Create
- After the application registration is created, click Settings
- Go to Required permissions
- Click Add
- Click Select an API
- Select Microsoft Graph and click Select
- Under Application Permissions *, check Invite guest users to the organization
- As an extra, I’ve also selected Read all users’ full profiles to enable me to show the users in the web app
- Click Select to select the permissions, then Done to finish adding API access.
IMPORTANT!
Click the Grant permissions button to actually grant the permissions to the application. An admin has to grant these permissions, you can do so by clicking the button. Any changes you make in the permissions you enable for the application require you to explicitly grant the permissions by clicking the button.
- Go to Keys
- Under Passwords, type a Key description, select a Duration and click Save
IMPORTANT!
Copy the Key value after you save, since you won’t be able to retrieve the key after you closed the blade.
* Application Permissions and Delegated permissions
I’ve explicitly said to check the permissions for the application under Application permissions. And there’s a reason to do this. You should use Delegated permissions when you want the application to call the API as the logged in user. When the application calls Graph as itself, use Application permissions. Since we want to enable everyone that uses the app to invite users, we’re using Application permissions.
2. Create and implement the Web App
- Create an ASP.NET web application. I created one using .NET Core 2.0 but you’re free to choose whatever is your preference.
- Add the Microsoft.Graph NuGet package
- Add the Active Directory Authentication Library NuGet package (Microsoft.IdentityModel.Clients.ActiveDirectory)
- Create something like an InviteUserModel, controller actions and views
- Create a ClientCredential with…
- The id of the application you created in step 1
- The Secret for the application you created in step 1
- Create an AuthenticationContext for your AAD tenant (something like
https://login.microsoftonline.com/<YOUR_AAD_TENANT>.onmicrosoft.com
) - Get a token for Microsoft Graph by calling AcquireToken on the AuthenticationContext
- Create a DelegateAuthProvider that adds the resulting token to the header of each request
Setting it all up should look something like this:
var clientCredential = new ClientCredential(_appId, _appSecret);
var authenticationContext = new AuthenticationContext($"https://login.microsoftonline.com/{_tenant}");
var authenticationResult = authenticationContext.AcquireTokenAsync("https://graph.microsoft.com", clientCredential).Result;
var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authenticationResult.AccessToken);
return Task.FromResult(0);
});
return new GraphServiceClient(delegateAuthProvider);
3. Use Microsoft Graph
Since I made an example that holds a GraphServiceClientHelper, this it what it looks like to use it:
var graphServiceClient = GraphServiceClientHelper.CreateGraphServiceClient();
var invitation = await graphServiceClient.Invitations.Request().AddAsync(new Invitation
{
InviteRedirectUrl = "https://localhost:xxx",
InvitedUserDisplayName = inviteUserModel.DisplayName,
InvitedUserEmailAddress = inviteUserModel.EmailAddress,
InvitedUserMessageInfo = new InvitedUserMessageInfo
{
CustomizedMessageBody = inviteUserModel.InviteMessage
},
SendInvitationMessage = inviteUserModel.SendInviteMessage
});
IMPORTANT!
The InviteRedirectUrl is a required parameter. It should hold the URL to which the invited user is forwarded after accepting the invitation.
Gotcha!
Please be advised that there are some differences between the V1.0 Graph API and the beta version. One example is that the beta version doesn’t support retrieving more than 100 items at a time. On the other hand, V1.0 doesn’t support expanding the MemberOf property, while the beta does support this. To call the beta version, use the constructor overload for GraphServiceClient that takes two parameters: baseUrl
and authenticationProvider
. You do not have to change the url of the resource you’re acquiring a token for. Tokens for Microsoft Graph work for both V1.0 and the beta version.
Initializing the GraphServiceClient for the beta version should look something like this:
new GraphServiceClient("https://graph.microsoft.com/beta", delegateAuthProvider);
Source code
I’ve hosted the (extremely simple) example on GitHub. You can find it here: rickvdbosch/MicrosoftGraphExample. If you have any issues completing this guide post a comment, or contact me.