Graph API for Entra ID (Azure AD) Object Management
Graph REST API for effective administration of user identities, groups, and devices is essential for organizations of all sizes.
Join the DZone community and get the full member experience.
Join For FreeAzure Active Directory (Azure AD) plays a crucial role in identity and access management; however, manually handling the lifecycles of these objects, such as adding new users, updating responsibilities, and deleting old accounts, can be challenging.
This is where Graph API comes in. By streamlining and automating the entire lifecycle management of Azure AD objects, Graph API ensures consistency, security, and scalability and reduces administrative oversight. In this article, we'll walk you through how to use Graph API to do just that.
By the end of it, you'll understand the Graph API, its uses, and how to optimize control of AAD objects. Let's dive right in.
Graph API for Lifecycle Management of Azure AD Objects
What Is Graph API?
From a mathematical and scientific point of view, a graph is a concept describing nodes and their connections. The Azure Active Directory has a graph-like model structure where the different entities (groups, users, applications) represent the nodes, and relationships (application assignments, group membership) represent the edges.
To navigate the content of AAD, we have the Graph API. This RESTful API provides a single endpoint for developers to access data and services. It also allows them to perform CRUD operations across various Microsoft services — such as Teams, Office 365, AAD, OneDrive, and more.
It has a set of standard queries used to retrieve metadata information and the data structure of a tenant's directory. Besides that, Graph API has differential queries that are used to synchronize AAD with other data stores.
The Uses of Graph API
Microsoft Graph API is a simple yet powerful interface primarily designed to simplify the way developers interact with Microsoft’s resources and services. So, what are some of its uses?
- Identity and access management. Through automated user provisioning, role-based access control, and conditional access policies for secure authentication and authorization.
- Centralized data access and management. Easily access and manipulate data across the Microsoft ecosystem with a unified endpoint.
- Handling event logistics. Administer events, such as sending meeting invites, scheduling meetings, etc., using Graph API to access Outlook Calendar.
- Managing user insights: Take advantage of Graph API to make data-driven decisions by analyzing user activity and engagement trends, or even integrate with Power BI to visualize data easily.
- Automating workflow: Streamline repetitive tasks such as creating and deleting accounts, tracking task progress, processing and responding to emails, etc.
Leveraging Graph API for Lifecycle Management of Azure AD Objects
Before exploring how to harness the power of Microsoft Graph API, let's first discuss Azure AD objects and the lifecycle management of these objects.
What Are Azure AD Objects?
An Azure AD object is any entity stored and managed in an active directory tenant. From the perspective of a non-developer, think of it as anything you want to manage within your Azure AD environment.
Here’s a breakdown of what it includes:
- User accounts – Individual users with unique IDs and passwords
- Group accounts – Users grouped based on roles and privileges
- Devices – Includes computers, phones, or any device connected to your Azure AD
- Applications – Software applications that can be integrated with your Azure AD
Lifecycle Management of Azure AD Objects
Lifecycle management is creating, updating, and removing user accounts, groups, and other directory objects over time. Some of its benefits include:
- Automated provisioning and de-provisioning. It helps you automatically create and delete user accounts, groups, and roles.
- Password reset. It allows users to reset their passwords themselves without needing any administrative guidance.
- Role-based access and control. Assign roles and privileges to the users.
- Conditional access. You can allow users to access certain resources based on certain conditions.
In essence, it allows organizations to manage and control
How to Authenticate and Register an Application With Azure AD for Microsoft Graph API Access
Accessing the Graph API requires your application to be authenticated with Microsoft's identity platform to get the access token. This authentication (known as Bearer authentication) is done through OAuth 2.0.
Once the token has been generated, it authorizes API requests to Microsoft Graph APIs. Here is a step-by-step guide to registering a new application with Azure AD:
Registering the Application
- Step 1: Go to Azure Portal.
- Step 2: Navigate through Azure Active Directory -> App Registrations -> New Registration.
- Step 3: Enter the name of your application and select a supported account type.
- Step 4: Now, copy the Application ID and Directory ID.
- Step 5: Create and copy the new client secret under Certificates and Secrets.
Assigning the API Permissions
- Step 6: Go to API Permissions.
- Step 7: Select Add a Permission -> Microsoft Graph.
- Step 8: Select the Microsoft Graph API permissions, for instance, User.ReadWrite.All and grant admin consent.
Authenticate Application With OAuth 2.0
- Step 9: Authenticate your application with OAuth 2.0 by requesting the OAuth 2.0 token endpoint.
Note: Ensure to replace [YOUR_TENANT_ID] with your ID.
Generating the Graph API Access Token
- Step 10: Now, generate the access token with the following code:
Import requests
# Azure AD App Details
tenant_id = "your-tenant-id"
client_id = "your-client-id"
client_secret = "your-client-secret"
scope = "https://graph.microsoft.com/.default" # Use .default to get app permissions
# Token endpoint
url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
# Request payload
payload = {
"client_id": client_id,
"scope": scope,
"client_secret": client_secret,
"grant_type": "client_credentials"
}
# Make the POST request
response = requests.post(url, data=payload)
# Check the response
if response.status_code == 200:
access_token = response.json().get("access_token")
print("Access Token:", access_token)
else:
print("Failed to get access token:", response.json())
In the above code:
tenant_id
: It is the Directory ID.client_id
: It is the Application ID.client_secret
: It is the secret we generated for the application.scope
: It refers to the permissions.grant_type
: It is set to the client's credentials.
Now that we have an access token, it's time to see how to manage the lifecycle of Azure AD objects with Microsoft Graph APIs:
Managing Service Principals, Groups and Roles
Before jumping in, service principal refers to an identity used by apps, services, or automated tools to access Azure resources securely.
To manage service principals, groups, and roles, the following permissions must be enabled:
- Application.ReadWrite.All
- Group.ReadWrite.All
- RoleManagement.ReadWrite.Directory
Once you have ensured the above, you can use the code snippets in the following sections to manage the groups, roles, and service principals.
Service Principals Management
Listing Service Principals
The following code gives you a list of all the service principals that are configured:
url = "https://graph.microsoft.com/v1.0/servicePrincipals"
response = requests.get(url, headers=headers)
print(response.json())
Creating a Service Principal
You can create a new service principal easily with the following code:
import requests
# Replace with access token we generated earlier
access_token = "[your_access_token]"
# API endpoint
url = "https://graph.microsoft.com/v1.0/servicePrincipals"
# Service principal payload
payload = {
"displayName": "My Service Principal",
"appId": "<application-id-of-the-app>"
}
# Headers
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json"
}
# Make the request
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 201:
print("Service Principal Created:", response.json())
else:
print("Error:", response.json())
Groups Management
Creating a Group
Create a new user group with the following code:
url = "https://graph.microsoft.com/v1.0/groups"
payload = {
"displayName": "Developers Team",
"mailEnabled": False,
"mailNickname": "devteam",
"securityEnabled": True
}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 201:
print("Group Created:", response.json())
else:
print("Error:", response.json())
Adding Members to the Group
To add new members to the group, the following is the sample code:
group_id = "[group-id]" # Replace with your group ID
user_id = "[user-id]" # Replace with your user ID
url = f"https://graph.microsoft.com/v1.0/groups/{group_id}/members/$ref"
payload = {
"@odata.id": f"https://graph.microsoft.com/v1.0/users/{user_id}"
}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 204:
print("Member Added to Group")
else:
print("Error:", response.json())
Deleting a Group
You can also delete a group with the following snippet:
group_id = "[group-id]"
url = f"https://graph.microsoft.com/v1.0/groups/{group_id}"
response = requests.delete(url, headers=headers)
if response.status_code == 204:
print("Group Deleted")
else:
print("Error:", response.json())
Removing a Member
If you want to remove a member from a group, use the following code:
group_id = "[group-id]"
member_id = "[user-or-service-principal-id]"
url = f"https://graph.microsoft.com/v1.0/groups/{group_id}/members/{member_id}/$ref"
response = requests.delete(url, headers=headers)
if response.status_code == 204:
print("Member Removed")
else:
print("Error:", response.json())
Roles Management
Assigning Roles
New roles can be assigned with the code given below:
role_id = "[role-id]" # Replace with the directory role ID
principal_id = "[service-principal-id]" # Replace with the service principal ID
url = "https://graph.microsoft.com/v1.0/directoryRoleAssignments"
payload = {
"principalId": principal_id,
"roleDefinitionId": f"{role_id}",
"directoryScopeId": "/"
}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 201:
print("Role Assigned:", response.json())
else:
print("Error:", response.json())
Listing Roles
If you want to view a list of all the roles, you can use this code:
url = "https://graph.microsoft.com/v1.0/directoryRoles"
response = requests.get(url, headers=headers)
if response.status_code == 200:
print("Roles:", response.json())
else:
print("Error:", response.json())
Other Lifecycle Management Tasks
Besides managing the principals, groups, and roles, you can perform the following lifecycle management tasks with Microsoft Graph APIs:
Provisioning New Users
- Onboarding new users on Azure AD.
- Endpoint:
POST https://graph.microsoft.com/v1.0/users
Updating User Information
- Change user roles, departments, or other information.
- Endpoint:
PATCH https://graph.microsoft.com/v1.0/users/{id}
Deactivating or Soft Deleting a User
- Temporarily delete or deactivate user accounts.
- Endpoint:
PATCH https://graph.microsoft.com/v1.0/users/{id}
Permanently Deleting a User
- Hard delete the users.
- Endpoint:
DELETE https://graph.microsoft.com/v1.0/directory/deletedItems/{id}
Tips for Using Graph APIs for Azure AD Cloud IAM
The following tips will help you to use Graph API to manage Azure AD Objects like a pro:
- Use a certified app-only authentication or the client secret for automation instead of an interactive login.
- Only assign the necessary Graph API access permissions.
- Keep an eye on the changes being made in users or groups with Delta Queries (/delta).
- Handle the API errors gracefully by calling
response.status_code
andresponse.json()
. - Review and audit all the Graph API changes by logging them.
Conclusion
Graph API isn't a new concept; however, its role in the lifecycle management of Azure AD Objects has become increasingly significant. With Graph API, organizations can automate repetitive tasks, thus minimizing errors, reducing administrative oversight, enhancing consistency and performance, and strengthening security by enforcing real-time conditional policies.
That’s not all, Graph API allows integration with various enterprise applications and workflows which not only improves the user experience but also operational efficiency.
As the digital world evolves toward adopting hybrid and multi-cloud environments, organizations need to use Graph API, which offers scalability, flexibility, and a futuristic approach to identity governance.
Opinions expressed by DZone contributors are their own.
Comments