Build PHP apps with Microsoft Graph and app-only authentication
This tutorial teaches you how to build a PHP console app that uses the Microsoft Graph API to access data using app-only authentication. App-only authentication is a good choice for background services or applications that need to access data for all users in an organization.
Note
To learn how to use Microsoft Graph to access data on behalf of a user, see this user (delegated) authentication tutorial.
In this tutorial, you will:
Tip
As an alternative to following this tutorial, you can download or clone the GitHub repository and follow the instructions in the README to register an application and configure the project.
Prerequisites
Before you start this tutorial, you should have PHP and Composer installed on your development machine.
You should also have a Microsoft work or school account with the Global administrator role. If you don't have a Microsoft 365 tenant, you might qualify for one through the Microsoft 365 Developer Program; for details, see the FAQ. Alternatively, you can sign up for a 1-month free trial or purchase a Microsoft 365 plan.
Note
This tutorial was written with PHP version 8.1.5 and Composer version 2.3.5. The steps in this guide may work with other versions, but that has not been tested.
Register the app in the portal
In this exercise you will register a new application in Azure Active Directory to enable app-only authentication. You can register an application using the Microsoft Entra admin center, or by using the Microsoft Graph PowerShell SDK.
Register application for app-only authentication
In this section you will register an application that supports app-only authentication using client credentials flow.
Open a browser and navigate to the Microsoft Entra admin center and login using a Global administrator account.
Select Microsoft Entra ID in the left-hand navigation, expand Identity, expand Applications, then select App registrations.
Select New registration. Enter a name for your application, for example,
Graph App-Only Auth Tutorial
.Set Supported account types to Accounts in this organizational directory only.
Leave Redirect URI empty.
Select Register. On the application's Overview page, copy the value of the Application (client) ID and Directory (tenant) ID and save them, you will need these values in the next step.
Select API permissions under Manage.
Remove the default User.Read permission under Configured permissions by selecting the ellipses (...) in its row and selecting Remove permission.
Select Add a permission, then Microsoft Graph.
Select Application permissions.
Select User.Read.All, then select Add permissions.
Select Grant admin consent for..., then select Yes to provide admin consent for the selected permission.
Select Certificates and secrets under Manage, then select New client secret.
Enter a description, choose a duration, and select Add.
Copy the secret from the Value column, you will need it in the next steps.
Important
This client secret is never shown again, so make sure you copy it now.
Note
Notice that, unlike the steps when registering for user authentication, in this section you did configure Microsoft Graph permissions on the app registration. This is because app-only auth uses the client credentials flow, which requires that permissions be configured on the app registration. See The .default scope for details.
Create a PHP console app
Begin by initializing a new Composer project. Open your command-line interface (CLI) in a directory where you want to create the project. Run the following command.
composer init
Answer the prompts. You can accept the defaults for most questions, but respond n
to the following:
Would you like to define your dependencies (require) interactively [yes]? n
Would you like to define your dev dependencies (require-dev) interactively [yes]? n
Add PSR-4 autoload mapping? Maps namespace "Microsoft\Graphapponlytutorial" to the entered relative path. [src/, n to skip]: n
Install dependencies
Before moving on, add some additional dependencies that you will use later.
- Microsoft Graph SDK for PHP to make calls to the Microsoft Graph.
- vlucas/phpdotenv for reading environment variables from .env files.
Run the following command in your CLI to install the dependencies.
composer require microsoft/microsoft-graph vlucas/phpdotenv
Load application settings
In this section you'll add the details of your app registration to the project.
Create a file in the root directory of your project named .env and add the following code.
CLIENT_ID=YOUR_CLIENT_ID_HERE CLIENT_SECRET=YOUR_CLIENT_SECRET_HERE_IF_USING_APP_ONLY TENANT_ID=YOUR_TENANT_ID_HERE_IF_USING_APP_ONLY
Update the values according to the following table.
Setting Value CLIENT_ID
The client ID of your app registration CLIENT_SECRET
The client secret of your app registration TENANT_ID
The tenant ID of your organization Important
If you're using source control such as git, now would be a good time to exclude the .env file from source control to avoid inadvertently leaking your app ID.
Design the app
In this section you will create a simple console-based menu.
Create a file in the root directory of your project named main.php. Add the opening and closing PHP tags.
<?php ?>
Add the following code between the PHP tags.
// Enable loading of Composer dependencies require_once realpath(__DIR__ . '/vendor/autoload.php'); require_once 'GraphHelper.php'; print('PHP Graph Tutorial'.PHP_EOL.PHP_EOL); // Load .env file $dotenv = Dotenv\Dotenv::createImmutable(__DIR__); $dotenv->load(); $dotenv->required(['CLIENT_ID', 'CLIENT_SECRET', 'TENANT_ID']); initializeGraph(); $choice = -1; while ($choice != 0) { echo('Please choose one of the following options:'.PHP_EOL); echo('0. Exit'.PHP_EOL); echo('1. Display access token'.PHP_EOL); echo('2. List users'.PHP_EOL); echo('3. Make a Graph call'.PHP_EOL); $choice = (int)readline(''); switch ($choice) { case 1: displayAccessToken(); break; case 2: listUsers(); break; case 3: makeGraphCall(); break; case 0: default: print('Goodbye...'.PHP_EOL); } }
Add the following placeholder methods at the end of the file before the closing PHP tag. You'll implement them in later steps.
function initializeGraph(): void { // TODO } function displayAccessToken(): void { // TODO } function listUsers(): void { // TODO } function makeGraphCall(): void { // TODO }
This implements a basic menu and reads the user's choice from the command line.
Add app-only authentication
In this section you will add app-only authentication to the application. This is required to obtain the necessary OAuth access token to call the Microsoft Graph.
Configure Graph client for app-only authentication
In this section you will use the PhpLeagueAuthenticationProvider
class to request an access token by using the client credentials flow.
Create a new file in the root directory of your project named GraphHelper.php. Add the following code.
<?php class GraphHelper { } ?>
Add the following
using
statements inside the PHP tags.use Microsoft\Graph\Core\Authentication\GraphPhpLeagueAccessTokenProvider; use Microsoft\Graph\Generated\Models; use Microsoft\Graph\Generated\Users\UsersRequestBuilderGetQueryParameters; use Microsoft\Graph\Generated\Users\UsersRequestBuilderGetRequestConfiguration; use Microsoft\Graph\GraphServiceClient; use Microsoft\Kiota\Authentication\Oauth\ClientCredentialContext;
Add the following code to the
GraphHelper
class.private static string $clientId = ''; private static string $clientSecret = ''; private static string $tenantId = ''; private static ClientCredentialContext $tokenContext; private static GraphServiceClient $appClient; public static function initializeGraphForAppOnlyAuth(): void { GraphHelper::$clientId = $_ENV['CLIENT_ID']; GraphHelper::$clientSecret = $_ENV['CLIENT_SECRET']; GraphHelper::$tenantId = $_ENV['TENANT_ID']; GraphHelper::$tokenContext = new ClientCredentialContext( GraphHelper::$tenantId, GraphHelper::$clientId, GraphHelper::$clientSecret); GraphHelper::$appClient = new GraphServiceClient( GraphHelper::$tokenContext, ['https://graph.microsoft.com/.default']); }
Replace the empty
initializeGraph
function in main.php with the following.function initializeGraph(): void { GraphHelper::initializeGraphForAppOnlyAuth(); }
This code loads information from the .env file, and initializes two properties, a ClientCredentialContext
object and a GraphServiceClient
object. The ClientCredentialContext
object will be used to authenticate requests, and the GraphServiceClient
object will be used to make calls to Microsoft Graph.
Test the client credentials flow
Next, add code to get an access token from the GraphHelper
.
Add the following function to the
GraphHelper
class.public static function getAppOnlyToken(): string { // Create an access token provider to get the token $tokenProvider = new GraphPhpLeagueAccessTokenProvider(GraphHelper::$tokenContext); return $tokenProvider ->getAuthorizationTokenAsync('https://graph.microsoft.com') ->wait(); }
Replace the empty
displayAccessToken
function in main.php with the following.function displayAccessToken(): void { try { $token = GraphHelper::getAppOnlyToken(); print('App-only token: '.$token.PHP_EOL.PHP_EOL); } catch (Exception $e) { print('Error getting access token: '.$e->getMessage().PHP_EOL.PHP_EOL); } }
Build and run the app. Enter
1
when prompted for an option. The application displays the access token it has fetched using the authentication information configured previously in the environment variables.$ php main.php PHP Graph Tutorial Please choose one of the following options: 0. Exit 1. Display access token 2. List users 3. Make a Graph call 1 App-only token: eyJ0eXAiOiJKV1QiLCJub25jZSI6IlVDTzRYOWtKYlNLVjVkRzJGenJqd2xvVUcwWS...
Tip
For validation and debugging purposes only, you can decode app-only access tokens using Microsoft's online token parser at https://jwt.ms. This can be useful if you encounter token errors when calling Microsoft Graph. For example, verifying that the
role
claim in the token contains the expected Microsoft Graph permission scopes.
List users
In this section you will add the ability to list all users in your Azure Active Directory using app-only authentication.
Add the following code to the
GraphHelper
class.public static function getUsers(): Models\UserCollectionResponse { $configuration = new UsersRequestBuilderGetRequestConfiguration(); $configuration->queryParameters = new UsersRequestBuilderGetQueryParameters(); // Only request specific properties $configuration->queryParameters->select = ['displayName','id','mail']; // Sort by display name $configuration->queryParameters->orderby = ['displayName']; // Get at most 25 results $configuration->queryParameters->top = 25; return GraphHelper::$appClient->users()->get($configuration)->wait(); }
Replace the empty
listUsers
function in main.php with the following.function listUsers(): void { try { $users = GraphHelper::getUsers(); // Output each user's details foreach ($users->getValue() as $user) { print('User: '.$user->getDisplayName().PHP_EOL); print(' ID: '.$user->getId().PHP_EOL); $email = $user->getMail(); $email = isset($email) ? $email : 'NO EMAIL'; print(' Email: '.$email.PHP_EOL); } $nextLink = $users->getOdataNextLink(); $moreAvailable = isset($nextLink) && $nextLink != '' ? 'True' : 'False'; print(PHP_EOL.'More users available? '.$moreAvailable.PHP_EOL.PHP_EOL); } catch (Exception $e) { print(PHP_EOL.'Error getting users: '.$e->getMessage().PHP_EOL.PHP_EOL); } }
Run the app, sign in, and choose option 2 to list users.
Please choose one of the following options: 0. Exit 1. Display access token 2. List users 3. Make a Graph call 2 User: Adele Vance ID: 05fb57bf-2653-4396-846d-2f210a91d9cf Email: AdeleV@contoso.com User: Alex Wilber ID: a36fe267-a437-4d24-b39e-7344774d606c Email: AlexW@contoso.com User: Allan Deyoung ID: 54cebbaa-2c56-47ec-b878-c8ff309746b0 Email: AllanD@contoso.com User: Bianca Pisani ID: 9a7dcbd0-72f0-48a9-a9fa-03cd46641d49 Email: NO EMAIL User: Brian Johnson (TAILSPIN) ID: a8989e40-be57-4c2e-bf0b-7cdc471e9cc4 Email: BrianJ@contoso.com ... More users available? true
Code explained
Consider the code in the getUsers
function.
- It gets a collection of users.
- It uses
queryParameters->select
to request specific properties - It uses
queryParameters->top
to limit the number of users returned - It uses
queryParameters->orderby
to sort the response
Optional: add your own code
In this section you will add your own Microsoft Graph capabilities to the application. This could be a code snippet from Microsoft Graph documentation or Graph Explorer, or code that you created. This section is optional.
Update the app
Add the following code to the
GraphHelper
class.public static function makeGraphCall(): void { // INSERT YOUR CODE HERE }
Replace the empty
makeGraphCall
function in main.php with the following.function makeGraphCall(): void { try { GraphHelper::makeGraphCall(); } catch (Exception $e) { print(PHP_EOL.'Error making Graph call'.PHP_EOL.PHP_EOL); } }
Choose an API
Find an API in Microsoft Graph you'd like to try. For example, the Create event API. You can use one of the examples in the API documentation, or create your own API request.
Configure permissions
Check the Permissions section of the reference documentation for your chosen API to see which authentication methods are supported. Some APIs don't support app-only, or personal Microsoft accounts, for example.
- To call an API with user authentication (if the API supports user (delegated) authentication), see the user (delegated) authentication tutorial.
- To call an API with app-only authentication (if the API supports it), add the required permission scope in the Azure AD admin center.
Add your code
Add your code into the makeGraphCall
function in GraphHelper.php.
Congratulations!
You've completed the PHP Microsoft Graph tutorial. Now that you have a working app that calls Microsoft Graph, you can experiment and add new features.
- Learn how to use user (delegated) authentication with the Microsoft Graph PHP SDK.
- Visit the Overview of Microsoft Graph to see all of the data you can access with Microsoft Graph.
PHP Samples
Have an issue with this section? If so, please give us some feedback so we can improve this section.