Overview of Users, Groups and Permissions in Microsoft Graph–Part 1

The concept of Microsoft Graph revolves around the thoughts of users & groups.

Among consumers of Microsoft 365 cloud services, a Microsoft Graph User is also one of them. The identity of the user is well protected, and its access is also managed effectively. To run businesses, the user’s data plays an important role. Through Microsoft Graph Services, this data is represented to businesses in real-time updates, rich contexts, and better understanding at depth level. The appropriate permissions are managed on the data accessibility via Microsoft Graph Services.

An Office 365 group is a core entity that collaborates with users. It connects with SharePoint development services, enabling a wide range of collaboration scenarios, task planning, teamwork, and more.

Feature Supporting services Description
Users Azure AD and most efficient,
collaboration, intelligence, and
education services
The user is at the core of Microsoft Graph,
around which many Microsoft Graph services
build user-centric functionality.
Groups Azure AD, OneDrive, OneNote,
Outlook, Teams, Planner
An Office 365 group provides an important
collaborative unit for users to share news, conversations,
files, notes, calendars, plans, and more.
Identity and
Access Management
Azure AD Creates and manages directory resources such
as users, groups, and applications. Manages
access to resources and data. Provides customers
access to sign-in and account risk data in Azure AD.

Note: The Bold Italic text must be supplied in accordance with one’s texts/tokens.

Integrating users’ data, Microsoft 365 services, and your apps

Integrating users’ data, Microsoft 365 services, and your apps

The primary focus of the Microsoft Graph is on users and groups. It casts a Microsoft 365 services network. It also features data management, data protection, and data extraction for assisting various business scenarios. Microsoft Graph allows accessibility of user data but doesn’t risk the data by managing appropriate authorization.

Working with Users in Microsoft Graph

Microsoft Graph lets you build rich app experiences based on users and their relationships with other users and groups, their mail, calendar, and files.

You can get to users through Microsoft Graph in two different ways:

  • By their ID, /users/{id | userPrincipalName}
  • By utilizing the /me alias for the signed-in user, which is the same as /users/{signed-in user’s id}

Authorization

We require one of the following permissions to access user operations. The first three permissions can be granted to an app by a user (no admin access required). The rest of the permissions can only be provided to an app by the administrator.

  • User.ReadBasic.All
  • User.Read
  • User.ReadWrite
  • User.Read.All
  • User.ReadWrite.All
  • Directory.Read.All
  • Directory.ReadWrite.All
  • Directory.AccessAsUser.All

Common Properties

The following compose the default set of properties that are returned when getting a user or listing users. These are a subset of all available properties. To fetch more sets of user properties, one can use the $select query parameter.

Property Description
id The unique identifier for the user.
businessPhones The user’s phone numbers.
displayName The name is displayed in the address book for the user.
givenName The first name of the user.
jobTitle The user’s job title.
mail The user’s email address.
mobilePhone The user’s cell phone number.
officeLocation The user’s physical office location.
preferredLanguage The user’s language of preference.
surname The last name of the user.
userPrincipalName The user’s principal name.

Common Operations

Note: Some of these operations require additional permissions.

Path Description
/users To get all the users of the organization.
/users/{id} To list a specific user by id.

Create New User

Using Microsoft Graph services, the creation of a new user is a relatively easy task. The user which is required to create is present in the request body. To create a new user, minimum required properties need to be supplied while in addition, any writable properties can also be provided.

Permissions

You require one of the following permissions to call this API.

Permission type Permissions (from least to most privileged)
Delegated (work or school account) 1.User.ReadWrite.All
2. Directory.ReadWrite.All
3. Directory.AccessAsUser.All
Delegated (personal Microsoft account) Not supported.
Application 1. User.ReadWrite.All
2.Directory.ReadWrite.All

Registering an Azure AD V2 App using Azure AD App Registration

We need to register an Azure Active Directory (Azure AD) application that will be used to communicate with the Microsoft Graph.

There are two popular endpoints in Azure AD to register applications, known as V1 and V2. Here, we are going to use the new experience Azure AD app registration portal and the recommended V2 endpoint to register the application as that is the ideal approach moving forward.

Registering an Azure AD V2 App
  • Open a browser and select App registrations in Azure AD Portal.App registrations
  • Click + New registration from the current blade tabs.New registration
  • Specify the following values on the Register an application page:
  • Name = msgraph-usermgmt-app (or any name that works for you)
  • Supported account types = Accounts in the current organizational directory only (e.g., TatvaSoft) <choose the value that applies to your needs>
  • Redirect URI = Web: https://localhost:8080

Note: The Redirect URI value can be altered at a later stage and can also be pointed to URI that isn’t hosted.

  • For registering an application, hit the Register button.Registering an application
  • The Application Overview page opens once the app registration completes. From this page, copy below two IDs as they will be required later.
    1. Application (client) ID
    2. Directory (tenant) IDApplication Overview
  • From the current blade navigation pane, select Manage > Authentication. Add second redirect URI https://app.getpostman.com/oauth2/callback and click Save. This URL will be used later while consuming the Microsoft Graph via Postman.Authentication
  • From the current blade navigation pane, select Manage > Certificates & secrets. Click the + New client secret. Specify the following values on Add a client secret dialog that appears:
  • Description = UserMgmtSecret
  • Expires = Never
  • Click Add.Certificates & secrets
  • Once the screen displays the newly created Client Secret, copy its Value to use it as required.

Important: Make sure you copy the client secret now, as it will never be shown again in the Azure portal.

Client Secret

Now for making the Microsoft Graph calls, assign the required permissions to the application. The permission is categorized into two below-mentioned sets.

Delegated Permissions Application Permissions
For the application which runs in the user context,
one can use this set of permission.
While using the Client-credential flow
(app only flow), this set of permission is utilized.
With the usage of this permission, one can
explicitly delegate the application to run on the user’s behalf.
With the usage of this permission, the application runs without any user context.

For creating a user in the organization via Microsoft Graph query, bring the newly created Azure AD Application in use. Accordingly, we will grant “User.ReadWrite.All” and “Directory.ReadWrite.All” application permissions.

  • From the current blade navigation pane, choose Manage > API permissions.
  • Hit on + Add a permission button and choose the Microsoft Graph under Microsoft APIs.API permissions
  • Choose the Delegated permissions.Delegated permissions
  • Check the box for “User.ReadWrite.All” permission after expanding the User category. Similarly, expand the Directory category and check the boxes for “Directory.ReadWrite.All” and “Directory.AccessAsUser.All” permissions. Hit the Add permissions button.
    Directory category
  • Now select the Application Permissions.Application Permissions
  • Check the box for “User.ReadWrite.All” permission after expanding the User category. Similarly, expand the Directory category and check the box for “Directory.ReadWrite.All” permission. Hit the Add permissions button.Add permissions

Note: You will notice that the Admin consent required column shows “Yes” besides selected permissions. Thus, it is concluded that before using the application for the execution of Microsoft Graph queries, the Azure Ad Admin must provide the permissions.

  • Click Grant admin consent for <tenantName> from the API Permissions screen, and after that, click Yes.
Grant admin consent

Note: To grant consent, one must be either Azure AD Domain Administrator or have a similar role.

Create a Flow to create a user using Microsoft Graph

You need to have an Application ID, a Secret Key, and your Tenant ID/Name to use Microsoft Graph in Microsoft Flow.

  • Browse the https://flow.microsoft.com, select My flows, and click New > Instant-from blank.
    Microsoft Flow
  • Add a Flow button as a trigger and select Manually trigger a flow.
    Add Flow button
  • Add a step (action) – Initialize variable. Add Name as “GraphUrl,” change the Type to “String,” and add the Value of the Graph URL https://graph.microsoft.com/v1.0/users.
    Initialize variable

Authenticating to Microsoft Graph from Flow

  • Add a step (action) – HTTP-HTTP. Rename the action to Get bearer token Change Method to “POST” for URI https://login.microsoft.com/{TENANTID}/oauth2/v2.0/token, use “Content-Type” with “application/x-www-form-urlencoded” as Headers.Use the following parameter-set for Body: client_id={APPLICATIONID/CLIENTID}&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret={CLIENTSECRET}&grant_type=client_credentials
    Get bearer tokenThe above call to the Azure AD authentication endpoint will give you OAuth 2.0 authorization bearer token, which will be utilized in the HTTP calls to Microsoft Graph endpoints. You need to parse the response using Data operations – Parse JSON action.However, parsing JSON requires that we have a schema or we have a sample payload of the JSON returned. At this point, we can run the flow to get the sample payload. Dig into the Flow execution details using Run history, check the return value of the HTTP action Get bearer token as shown below. Copy the content of the Body.Get bearer token
  • Paste the copied value as a sample payload for Parse JSON action and then click Done.Parse JSON action
  • Your Parse JSON action would look like the one below.Parse JSON

Calling Microsoft Graph API from Flow

Finally, we are ready to make the actual HTTP call to the Graph endpoint for creating a new User.

  • Add an action HTTP-HTTP. Rename the action to Create a new Office 365 user. In this case, we select “POST” as the Method, and the URI of the endpoint is https://graph.microsoft.com/v1.0/users, which is the “GraphUrl” variable initialized earlier. In the Header section, we add two headers
  • “Authorization” and use parsed values “token_type” which is the bearer token and “access_token” which will be different each time.
  • “Content-Type” which is “application/json.”
  • Provide a JSON representation of the user object in the request body.
Action - Create new Office 365 user -> Body
{
	"accountEnabled": true,
	"displayName": "Test Azure user",
	"mailNickname": "TAUser",
	"userPrincipalName": "testazure@.onmicrosoft.com",
	"passwordProfile":
	{
		"forceChangePasswordNextSignIn": false,
		"password": " "
	}
}
Create new Office 365 User

At this point, your flow can create new Office 365 Users. Run and test the flow. Check the Office 365 active users and search for the newly created user.

Check the Office 365 active users

Perform action on groups in Microsoft Graph

The users and other principals, who are responsible for sharing access to the resources of either Microsoft services or one’s app, are encapsulated as part of Groups. As per the requirement, the APIs which are provisioned by Microsoft Graph can be used for the creation and management of the various groups and the group functionality. Admin consent is required in all group-related operations.

Note: Only work or school accounts are used to create Groups. While Groups are not supported with Personal Microsoft accounts.

Type Use case groupType mail-enabled security-enabled Can be created via
API?
Office 365 groups With Microsoft shared online resources, it provides
user collaboration.
[“Unified”] true false Yes
Security groups In-app resources, controls user access. [] false true Yes
Mail-enabled
security groups
In-app resources, it manages user access
along with a shared group mailbox.
[] true true No
Distribution groups Mail to group members is distributed by it. Office
365 groups are recommended cause of its richer
resources collection.
[] true false No

Create a Group

You can use Microsoft Graph services to create a new group that helps introduce more governance to your enterprise. Although different sources such as Outlook, Microsoft Teams, Planner, Power BI, SharePoint development services, and so on support groups’ creation, it seems there are very few large organizations in the real world supporting those scenarios. Perhaps it may be important to collect metadata information about the requestor/group/business unit/division, or perhaps you want an admin to check it is a genuine/justified request. Or maybe SharePoint developers need to verify whether there is already a SharePoint site for the scenario to Groupify the site instead.

Create a new group from the below-mentioned groups in the body of the request, as specified.

  • Office 365 Group (unified group)
  • Security group

By default, for each group, the CREATE operation returns only a subset of the properties. One can specify the properties, which are not returned by default, in a $select OData query option of a GET operation to get those properties.

Note: The creation of a team is not currently supported via the Microsoft Graph REST API even though the Microsoft Teams is built on Office 365 groups. One can manage a team that was created in the Microsoft Teams UI using the other group APIs.

Permissions

Azure AD application needs to grant one of the following permissions to call this API.

Permission type Permissions (from least to most privileged)
Delegated (work or school account) 1. Group.ReadWrite.All
2. Directory.ReadWrite.All
3. Directory.AccessAsUser.All
Delegated (personal Microsoft account) Not supported.
Application 1. Group.ReadWrite.All
2. Directory.ReadWrite.All

Configure Azure AD application with required permissions

We need to register an application and grant it permissions to create Groups and add users to them. We will use the same Azure AD app registered earlier while creating users.

  • Open the browser and navigate to the App registrations in Azure AD Portal
  • Open “msgraph-usermgmt-app” registered earlier.
  • Click the API permissions in the current blade navigation pane. Hit on the + Add a permission button. Select the Microsoft Graph under Microsoft APIs.App registrations in Azure AD Portal
  • Select the Delegated permissions.Delegated permissions for Group Action
  • Expand the Group category and check the box for “Group.ReadWrite.All” permission. Click on the Add permissions button.Add permissions for Group

Note: “Directory.ReadWrite.All” and “Directory.AccessAsUser.All” delegated permissions are already granted earlier while creating a user.

  • Similarly, select Application Permissions.Application Permissions for Group
  • Expand the Group category and check the box for “Group.ReadWrite.All” permission. Hit on the Add permissions button.Add permissions Group Category

Note: Application permission “Directory.ReadWrite.All” is already granted earlier while adding a new user.

  • As permissions have changed, the Admins are required to consent again, whether they have already done previously or not. On the API Permissions screen, click Grant admin consent for <tenantName>, then click Yes.
    Grant admin consent for Group

Create SharePoint lists for group requests

SharePoint developer can create a custom list “Group requests” for users and/or admins when they need to register a new workspace for their team, containing the below columns:

  • Group display name – Rename Title field
  • Group short name
  • Group description
  • The newly created list view looks like the one below.
    Group requests
  • The “Group Requests” new item form looks like the one below.
    Group Requests new item form
  • For tracking successfully created Groups, create a 2nd SharePoint list named “Created groups.” You can include a field “Group ID”, however, you can also store group metadata such as URL and Owner/s fields too.
    Created groups

Implementing controlled Group provisioning using a Flow and the Graph

  • Open https://flow.microsoft.com, select My flows and click New -> Instant-from blank.Instant-from blank
  • Add When an item is created, SharePoint triggers. Rename the trigger When an item is created in the Group requests list. Select Site Address and required List Name as “Group requests.”
    List Name
  • Add an action HTTP-HTTP. Rename the action to Create Office 365 Group (team space). Change Method to “POST” for URI https://graph.microsoft.com/v1.0/groups, use “Content-Type” with “application/json” and “Content-Length” with “244” as Headers
  • Add the Body as below.
    Action: Create Office 365 Group (team space) -> Body
    {
      "description": triggerBody()?['Group_x0020_description'],
      "displayName": triggerBody()?['Title'],
      "groupTypes": [
        "Unified"
      ],
      "mailEnabled": true,
      "mailNickname": triggerBody()?['Group_x0020_short_x0020_name'],
      "securityEnabled": false
    }
  • Click Show advanced options. Set Authentication to “Active Directory OAuth,” enter your Tenant name or Id, set Audience to https://graph.microsoft.com, pass Application ID/Client ID copied earlier, set Credential Type to “Secret,” and pass the key fetched earlier as Secret.
    Show advanced options
  • Add Data Operations – Parse JSON action to get the ID of the group that was just created so that we can add a Group owner later and log the Group ID to the “Created groups” list. Rename the operation to Parse JSON (created Group details).
  • Parse response body “body(‘Create_Office_365_Group_(team_space)’)” input in Content from the previous action and paste the following into the Schema box.
    Operation - Parse JSON (created Group details) -> Schema
    {
    	"type": "object",
    	"properties":
    	{
    		"id":
    		{
    			"type": "string"
    		},
    		"description":
    		{
    			"type":
    			[
    				"string",
    				"null"
    			]
    		},
    		"displayName":
    		{
    			"type":
    			[
    				"string",
    				"null"
    			]
    		},
    		"groupTypes":
    		{
    			"type": "array",
    			"items":
    			{
    				"type": "string"
    			}
    		},
    		"mail":
    		{
    			"type": "string"
    		},
    		"mailEnabled":
    		{
    			"type": "boolean"
    		},
    		"mailNickname":
    		{
    			"type": "string"
    		},
    		"securityEnabled":
    		{
    			"type": "boolean"
    		}
    	}
    }
  • Add SharePoint – Create item action. Rename the action to Add item to Created groups list. Select the required Site Address and List Name as “Created groups.” Drop-in variables from the previous Parse JSON action to obtain the Group ID as “body(‘Parse_JSON_(created_Group_details)’)?[‘id’]” and Title as display name i.e “body(‘Parse_JSON_(created_Group_details)’)?[‘displayName’]”.
    SharePoint - Create item
  • Add an action HTTP-HTTP. Rename the action to Get user. In this action, we will make a GET request to the https://graph.microsoft.com/v1.0/users/[UserID] Graph endpoint. At the end of the URL, enter the variable for the UserID, which is the ID or UPN of the user. From the first action in the flow (When a new item is added to the “Groups requests” list), use the “Created by e-mail” variable, i.e. “triggerBody()?[‘Author’]?[‘Email’]” if the email addresses are the same as UPNs. Hit on the Show advanced options. Set Authentication to “Active Directory OAuth,” enter your Tenant name or Id, set Audience to https://graph.microsoft.com, pass Application ID or Client ID copied earlier, set Credential Type to “Secret,” and pass the key fetched earlier as Secret.
    Rename the action to Get user
  • Add Data Operations – Parse JSON action to get the user ID of the group requestor so that we can add the user as an owner of the newly created group. Rename the operation to Parse JSON (Group requestor). Parse response body “body(Get_user’)” input in Content from the previous action and paste the following into the Schema box:
    Operation - Parse JSON (Group requestor) -> Schema
    {
    	"type": "object",
    	"properties": 
    	{
    		"businessPhones": {
    			"type": "array",
    			"items":
    			{
    				"type":
    				[
    					"string",
    					"null"
    				]
    			}
    		},
    		"userPrincipalName":
    		{
    			"type": "string"
    		},
    		"id":
    		{
    			"type": "string"
    		}
    	}
    }
  • Add a step (action) – HTTP-HTTP to add the owner to the newly created group. Rename the action to Add owner to created Group. In this action, we will make a POST Method request to https://graph.microsoft.com/v1.0/groups/[Group ID]/owners/$ref Graph endpoint. Drop-in variables from earlier action as appropriate to add “Group ID” “body(‘Parse_JSON_(created_Group_details)’)?[‘id’]” in the URI and the “User ID” “body(‘Parse_JSON_(Group_requestor)’)?[‘id’]” in the request body.
    Action - Add owner to created Group -> Body
    {
      "@{concat('@','odata.id')}": "https://graph.microsoft.com/v1.0/users/@{body('Parse_JSON_(Group_requestor)')?['id']}"
    }
  • Hit on the Show advanced options. Set Authentication to “Active Directory OAuth,” enter your Tenant name or Id, set Audience to https://graph.microsoft.com, enter Application ID/Client ID copied earlier, set Credential Type to “Secret,” and pass the key fetched earlier as Secret.
    Add Owner to created Group
  • Test the flow by creating an item in the “Group requests” list.
    Test the flow
  • Check the run to see if the flow ran successfully.
    Check the run
  • At this point, your flow can create a new Office 365 Group. Check the Office 365 groups and search for the newly created group. Also, check if newly created group entries exist in the “Created groups” list.
    Create new Office 365 GroupCreated groups list
  • You can observe that the group requestor is also added as an owner of the group.
    Manage Owners

Conclusion

It’s highly favorable to create new Office 365 groups (also add users as an owner based on requirement) and users purely through MS Flow using the right combination of Microsoft Graph requests and parsing the responses returned, with no custom code such as an Azure function needed. The next blog in this series will walk through the process of assigning permissions using unified groups.

profile-image
Shital Patel

Shital Patel is VP at TatvaSoft with a high-level of proficiency and technical precision in SharePoint Development. His experience of the last two decades has helped businesses to solve complex challenges resulting in growth and performance of Startups to Fortune 500 companies.

Related Service

Know more about SharePoint Development services

Learn more

Want to Hire Skilled Developers?


    Comments

    • Leave a message...