DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Develop Microservices Using Azure Functions, API Management
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 7)
  • Zero to AI Hero, Part 3: Unleashing the Power of Agents in Semantic Kernel
  • Exploration of Azure OpenAI

Trending

  • How to Convert Between PDF and TIFF in Java
  • Key Considerations in Cross-Model Migration
  • Beyond Microservices: The Emerging Post-Monolith Architecture for 2025
  • Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Graph API for Entra ID (Azure AD) Object Management

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.

By 
Anant Wairagade user avatar
Anant Wairagade
·
Mar. 21, 25 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
4.8K Views

Join the DZone community and get the full member experience.

Join For Free

Azure 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:
Python
 
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:

Python
 
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:

Python
 
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:

Python
 
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:

Python
 
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:

Python
 
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:

Python
 
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: 

Python
 
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:

Python
 
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 and response.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.

API azure Graph (Unix) Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • Develop Microservices Using Azure Functions, API Management
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 7)
  • Zero to AI Hero, Part 3: Unleashing the Power of Agents in Semantic Kernel
  • Exploration of Azure OpenAI

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: