Düzenle

Aracılığıyla paylaş


Build API clients for PHP with Microsoft identity authentication

In this tutorial, you generate an API client that uses Microsoft identity authentication to access Microsoft Graph.

Required tools

Create a project

Run the following commands in the directory where you want to create a new project.

composer init

Add dependencies

Before you can compile and run the generated API client, you need to make sure the generated source files are part of a project with the required dependencies. Your project must have a reference to the abstraction package. Additionally, you must either use the Kiota default implementations or provide your own custom implementations of the following packages.

For this tutorial, use the default implementations.

Run the following commands to get the required dependencies.

composer require microsoft/kiota-abstractions
composer require microsoft/kiota-http-guzzle
composer require microsoft/kiota-authentication-phpleague
composer require microsoft/kiota-serialization-json
composer require microsoft/kiota-serialization-text

Generate the API client

Kiota generates API clients from OpenAPI documents. Create a file named get-me.yml and add the following.

openapi: 3.0.3
info:
  title: Microsoft Graph get user API
  version: 1.0.0
servers:
  - url: https://graph.microsoft.com/v1.0/
paths:
  /me:
    get:
      responses:
        200:
          description: Success!
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/microsoft.graph.user"
components:
  schemas:
    microsoft.graph.user:
      type: object
      properties:
        id:
          type: string
        displayName:
          type: string

You can then use the Kiota command line tool to generate the API client classes.

kiota generate -l PHP -d get-me.yml -c GraphApiClient -n GetUser\Client -o ./client

Add the following to your composer.json to set your namespaces correctly:

"autoload": {
    "psr-4": {
        "GetUser\\Client\\": "client/"
    }
}

To ensure the newly generated classes can be imported, update the autoload paths using:

composer dumpautoload

Register an application

To be able to authenticate with the Microsoft Entra identity platform and get an access token for Microsoft Graph, you need to create an application registration. You can install the Microsoft Graph PowerShell SDK and use it to create the app registration, or register the app manually in the Microsoft Entra admin center.

The following instructions register an app and enable authorization code flow for authentication.

  1. Open a browser and navigate to the Azure Active Directory admin center. Sign in with your Azure account.

  2. Select Azure Active Directory in the left-hand navigation, then select App registrations under Manage.

  3. Select New registration. On the Register an application page, set the values as follows.

    • Set Name to Kiota Test Client.
    • Set Supported account types to Accounts in any organizational directory and personal Microsoft accounts.
    • Set Redirect URI platform to Web, and set the value to http://localhost.
  4. Select Register. On the Overview page, copy the value of the Application (client) ID and save it.

  5. Select Certificates & secrets under Manage. Select the New client secret button. Enter a value in Description and select one of the options for Expires and select Add.

  6. Copy the Value of the new secret before you leave this page. It is never displayed again. Save the value for later.

Create the client application

Create a file in the root of the project named GetUser.php and add the following code. Replace the $clientId and $clientSecret with your credentials from the previous step.

Use the following steps to get an authorization code.

Important

Authorization codes are short-lived, typically expiring after 10 minutes. You should get a new authorization code just before running the example.

  1. Open your browser and paste in the following URL, replacing YOUR_CLIENT_ID with the client ID of your app registration.

    https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=http%3A%2F%2Flocalhost&response_mode=query&scope=User.Read
    
  2. Sign in with your Microsoft account. Review the requested permissions and grant consent to continue.

  3. Once authentication completes, your browser will redirect to http://localhost. The browser displays an error that can be safely ignored.

  4. Copy the URL from your browser's address bar.

  5. Copy everything in the URL between code= and &. This value is the authorization code.

Replace the $authorizationCode with your authorization code.

<?php

use GetUser\Client\GraphApiClient;
use Microsoft\Kiota\Abstractions\ApiException;
use Microsoft\Kiota\Authentication\Oauth\AuthorizationCodeContext;
use Microsoft\Kiota\Authentication\PhpLeagueAuthenticationProvider;
use Microsoft\Kiota\Http\GuzzleRequestAdapter;

require __DIR__.'/vendor/autoload.php';

try {
    $clientId = 'clientId';
    $clientSecret = 'secret';
    $authorizationCode = 'authCode';

    $tenantId = 'common';
    $redirectUri = 'http://localhost';

    // The auth provider will only authorize requests to
    // the allowed hosts, in this case Microsoft Graph
    $allowedHosts = ['graph.microsoft.com'];
    $scopes = ['User.Read'];

    $tokenRequestContext = new AuthorizationCodeContext(
        $tenantId,
        $clientId,
        $clientSecret,
        $authorizationCode,
        $redirectUri
    );

    $authProvider = new PhpLeagueAuthenticationProvider($tokenRequestContext, $scopes, $allowedHosts);
    $requestAdapter = new GuzzleRequestAdapter($authProvider);
    $client = new GraphApiClient($requestAdapter);

    $me = $client->me()->get()->wait();
    echo "Hello {$me->getDisplayName()}, your ID is {$me->getId()}";

} catch (ApiException $ex) {
    echo $ex->getMessage();
}
?>

Note

This example uses the AuthorizationCodeContext class. You can use any of the credential classes from the kiota-authentication-phpleague library.

Run the application

To start the application, run the following command in your project directory.

php GetUser.php

See also