Microsoft Graph PHP SDK

repository·main·Indexed 20 days ago

https://github.com/microsoftgraph/msgraph-sdk-php

A fluent, type-safe PHP SDK for interacting with the Microsoft Graph API v1.0. It features an asynchronous architecture using promises and supports various OAuth 2.0 authentication flows, including Client Credentials, Authorization Code, and On-Behalf-Of. Requires PHP 8.2 or later.

Tokens
23.2K
Snippets
59
Records
68
Agent score
68%

What's inside microsoftgraph-msgraph-sdk-php

  1. Use the Authentication Provider in v2.0.0

    main

    Version 2.0.0 introduces an Authentication Provider that handles token fetching, caching, and refreshing automatically. It wraps around the PHP League's OAuth 2.0 client via GraphPhpLeagueAuthenticationProvider.

    Supported flows include client_credentials, authorization_code, and on_behalf_of. It also supports certificate-based authentication.

    In v1.x, you had to manually manage access tokens and pass them to the client or individual requests. In v2.0, you initialize a TokenRequestContext and pass it to the provider.

    // v2.0 implementation
    $tokenRequestContext = new AuthorizationCodeContext(
        'tenantId',
        'clientId',
        'clientSecret',
        'authCode',
        'redirectUri'
    );
    $scopes = ['User.Read', 'Mail.Read'];
    $authProvider = new GraphPhpLeagueAuthenticationProvider($tokenRequestContext, $scopes);
  2. Create a Token Request Context

    main

    A TokenRequestContext contains the credentials used to authenticate requests. The SDK supports several OAuth 2.0 flows through different context classes. These contexts are passed to an authentication provider that handles fetching, caching, and refreshing access tokens.

    Client Credentials Flow (App-only access)

    Use ClientCredentialContext to get access without a user (service-to-service authentication).

    Authorization Code Flow (User delegation)

    Use AuthorizationCodeContext to get access on behalf of a user. Note that your application must handle the redirect to the Microsoft Identity login page to obtain the authCode required for this context.

    // Client Credentials (No user)
    use Microsoft\Kiota\Authentication\Oauth\ClientCredentialContext;
    
    $tokenRequestContext = new ClientCredentialContext(
        'tenantId',
        'clientId',
        'clientSecret'
    );
    
    // Authorization Code (On behalf of a user)
    use Microsoft\Kiota\Authentication\Oauth\AuthorizationCodeContext;
    
    $tokenRequestContext = new AuthorizationCodeContext(
        'tenantId',
        'clientId',
        'clientSecret',
        'authCode',
        'redirectUri'
    );
  3. How access token management works in the SDK

    main

    The GraphServiceClient uses a TokenRequestContext to request access and refresh tokens. By default, these tokens are stored in an InMemoryAccessTokenCache, which lives in the PHP process and is destroyed when the process terminates.

    To ensure the correct token is retrieved, the SDK generates a unique cache key based on the permissions type:

    • Application permissions (no signed-in user): {tenantId}-{clientId}
    • Delegated permissions (signed-in user): {tenantId}-{clientId}-{userId}

    The cache stores PHPLeague AccessToken objects, which contain the access_token, its expiry, and an optional refresh_token.

  4. Use the Microsoft Graph Beta SDK for Beta API access

    main
    The standard msgraph-sdk-php repository targets the v1.0 Microsoft Graph API. If you need to access features or endpoints available only in the Beta version of the Microsoft Graph API, you should use the dedicated Beta SDK available on Packagist: microsoft/microsoft-graph-beta.
  5. Page through a collection using PageIterator

    main

    For large result sets, use the PageIterator. It automatically handles @odata.nextLink to fetch subsequent pages. You provide an initial response and the request adapter. The iterate() method accepts a callback that is executed for each item; returning false from the callback pauses the iteration.

    use Microsoft\Graph\Core\Tasks\PageIterator;
    use Microsoft\Graph\Generated\Models\Message;
    use DateTimeInterface;
    
    $messages = $graphServiceClient->users()->byUserId(USER_ID)->messages()->get()->wait();
    
    $pageIterator = new PageIterator($messages, $graphServiceClient->getRequestAdapter());
    
    $counter = 0;
    $callback = function (Message $message) use (&$counter) {
        echo "Subject: {$message->getSubject()}, Received at: {$message->getReceivedDateTime()->format(DateTimeInterface::RFC2822)}\n";
        $counter ++;
        return ($counter % 5 != 0);
    };
    
    while ($pageIterator->hasNext()) {
        // iteration pauses and resumes after every 5 messages
        $pageIterator->iterate($callback);
    
        echo "\nPaused iteration...Total messages: {$counter}\n\n";
    }
  6. Get started with the Microsoft Graph SDK for PHP

    main

    To begin using the Microsoft Graph SDK, you must follow a sequence of setup steps:

    1. Register your application in the Microsoft identity platform to obtain credentials.
    2. Create a Token Request Context to handle authentication.
    3. Initialize a GraphServiceClient to serve as the main entry point for API calls.
    4. Call Microsoft Graph using the v1.0 endpoint and provided PHP models.

    For detailed step-by-step instructions, refer to the Getting Started guide.

  7. Configure Continuous Access Evaluation (CAE)

    main

    Continuous Access Evaluation (CAE) is disabled by default. When enabled, if the Microsoft Graph API returns a claims challenge, the SDK attempts to refresh the access token once. If that fails, it executes a custom callback provided by the developer to re-authenticate the user.

    To use CAE:

    1. Set setCAEEnabled(true) on your TokenRequestContext.
    2. Implement setCAERedirectCallback() to handle the asynchronous re-authentication logic and return a new TokenRequestContext.
    3. Wrap calls in a try-catch block to handle ContinuousAccessEvaluationException if the re-authentication fails to resolve the challenge.
    $tokenRequestContext = new AuthorizationCodeContext(
        'tenantId',
        'clientId',
        'clientSecret',
        'authCode',
        'redirectUri'
    );
    $graphServiceClient = new GraphServiceClient($tokenRequestContext);
    
    $tokenRequestContext->setCAEEnabled(true);
    $tokenRequestContext->setCAERedirectCallback(function (string $claims) {
        // your app makes the user log in again asynchronously
        return yourCustomLoginAsync()->then(
            function (string $authCode) {
                $newTokenRequestContext = new AuthorizationCodeContext(
                    'tenantId',
                    'clientId',
                    'clientSecret',
                    $authCode,
                    'redirectUri'
                );
                return $newTokenRequestContext;
            }
        );
    });
    
    try {
        $numUsers = $graphServiceClient->users()->count()->get()->wait();
    } catch (ContinuousAccessEvaluationException $ex) {
        echo $ex->getError()->getMessage();
    }
  8. Initialize GraphServiceClient with an existing access token

    main
    For applications that already manage tokens (e.g., in a database or session), you can initialize the GraphServiceClient by providing an AccessTokenCache implementation pre-populated with your tokens. The SDK will check this cache before attempting to request a new token. If the token is expired but a refresh token is present, the SDK will automatically refresh it and update the cache.
  9. Initialize a GraphServiceClient using Client Credentials (Application Permissions)

    main

    To make requests without a signed-in user (using application permissions), use the ClientCredentialContext. If no $scopes are explicitly provided, the SDK defaults to using https://graph.microsoft.com/.default.

    use Microsoft\Graph\GraphServiceClient;
    use Microsoft\Kiota\Authentication\Oauth\ClientCredentialContext;
    
    // Uses https://graph.microsoft.com/.default scopes if none are specified
    $tokenRequestContext = new ClientCredentialContext(
        'tenantId',
        'clientId',
        'clientSecret'
    );
    $graphServiceClient = new GraphServiceClient($tokenRequestContext);
  10. Access Beta models via the Microsoft Graph Beta SDK

    main

    As of version 2.0.0, the main microsoft/microsoft-graph package only contains models matching the v1.0 API metadata. Beta models have been moved to a separate package to allow the main SDK to follow strict Semantic Versioning.

    To use Beta models, add the following to your composer.json:

     "require": {
        "microsoft/microsoft-graph-beta": "^2.0.0"
    }
  11. Use a custom AccessTokenCache implementation

    main

    To persist tokens across different PHP processes (e.g., in a database or Redis), implement the AccessTokenCache interface. When the SDK performs a request, it will call persistAccessToken() to save the token.

    To ensure your custom cache aligns with the SDK's lookup logic, you should use the cache key generated by the TokenRequestContext. You can manually set this key using $tokenRequestContext->setCacheKey($accessToken).

    $accessToken = new AccessToken([
        'access_token' => $accessToken,
        'refresh_token' => $refreshToken,
        'expires' => ...
    ]);
    
    $tokenRequestContext->setCacheKey($accessToken);
    
    // init custom cache with tokens mapped to specific user/app using $tokenRequestContext->getCacheKey()
    $customCache = new CustomCache($tokenRequestContext->getCacheKey(), $accessToken);
    
    // init graph client
    $graphServiceClient = GraphServiceClient::createWithAuthenticationProvider(
        GraphPhpLeagueAuthenticationProvider::createWithAccessTokenProvider(
            GraphPhpLeagueAccessTokenProvider::createWithCache(
                $customCache,
                $tokenRequestContext,
                $scopes
            )
        )
    );