|
| 1 | +# Usage Examples |
| 2 | + |
| 3 | +## Creating a Graph client |
| 4 | +This creates a default Graph client that uses `https://graph.microsoft.com` as the default base URL and default configured Guzzle HTTP client to make the requests. |
| 5 | + |
| 6 | +To make requests with a signed-in user, you can initialise an `AuthorizationCodeContext` with the code returned by Microsoft Identity after redirecting the |
| 7 | +user to the sign-in page. The same redirect URI provided while requesting the auth code is required: |
| 8 | + |
| 9 | +```php |
| 10 | + |
| 11 | +use Microsoft\Graph\GraphServiceClient; |
| 12 | +use Microsoft\Kiota\Authentication\Oauth\AuthorizationCodeContext; |
| 13 | + |
| 14 | +$tokenRequestContext = new AuthorizationCodeContext( |
| 15 | + 'tenantId', |
| 16 | + 'clientId', |
| 17 | + 'clientSecret', |
| 18 | + 'authCode', |
| 19 | + 'redirectUri' |
| 20 | +); |
| 21 | +$scopes = ['User.Read', 'Mail.ReadWrite']; |
| 22 | +$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes); |
| 23 | + |
| 24 | +``` |
| 25 | + |
| 26 | +To make requests on behalf of an already signed in user, where your front-end application has already acquired an access token for the user, you can use the `OnBehalfOfContext` which uses the [On-Behalf-Of flow](https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow) to fetch |
| 27 | +an access token for your backend application to access the Microsoft Graph API. To do this, you pass the already acquired access token as the "assertion"; |
| 28 | + |
| 29 | +```php |
| 30 | +use Microsoft\Graph\GraphServiceClient; |
| 31 | +use Microsoft\Kiota\Authentication\Oauth\OnBehalfOfContext; |
| 32 | + |
| 33 | +$tokenRequestContext = new OnBehalfOfContext( |
| 34 | + 'tenantId', |
| 35 | + 'clientId', |
| 36 | + 'clientSecret', |
| 37 | + 'assertion' |
| 38 | +); |
| 39 | + |
| 40 | +$scopes = ['User.Read', 'Mail.ReadWrite']; |
| 41 | +$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes); |
| 42 | + |
| 43 | +``` |
| 44 | + |
| 45 | + |
| 46 | +To make requests without a signed-in user (using application permissions), you can initialise a `ClientCredentialsContext` object: |
| 47 | + |
| 48 | +```php |
| 49 | +use Microsoft\Graph\GraphServiceClient; |
| 50 | +use Microsoft\Kiota\Authentication\Oauth\ClientCredentialContext; |
| 51 | + |
| 52 | +// Uses https://graph.microsoft.com/.default scopes if none are specified |
| 53 | +$tokenRequestContext = new ClientCredentialContext( |
| 54 | + 'tenantId', |
| 55 | + 'clientId', |
| 56 | + 'clientSecret' |
| 57 | +); |
| 58 | +$graphServiceClient = new GraphServiceClient($tokenRequestContext); |
| 59 | + |
| 60 | +``` |
| 61 | + |
| 62 | +Using a custom National Cloud deployment: |
| 63 | +```php |
| 64 | +$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes, NationalCloud::CHINA); |
| 65 | +``` |
| 66 | + |
| 67 | +Customizing the default Guzzle client: |
| 68 | +```php |
| 69 | + |
| 70 | +use Microsoft\Graph\Core\GraphClientFactory; |
| 71 | +use Microsoft\Graph\GraphRequestAdapter; |
| 72 | +use Microsoft\Graph\GraphServiceClient; |
| 73 | +use Microsoft\Graph\Core\Authentication\GraphPhpLeagueAuthenticationProvider; |
| 74 | + |
| 75 | +$tokenRequestContext = new ClientCredentialContext( |
| 76 | + 'tenantId', |
| 77 | + 'clientId', |
| 78 | + 'clientSecret' |
| 79 | +); |
| 80 | +$authProvider = new GraphPhpLeagueAuthenticationProvider($tokenRequestContext); |
| 81 | +$guzzleConfig = [ |
| 82 | + // your custom config |
| 83 | +]; |
| 84 | +$httpClient = GraphClientFactory::createWithConfig($guzzleConfig); |
| 85 | +$requestAdapter = new GraphRequestAdapter($authProvider, $httpClient); |
| 86 | +$graphServiceClient = GraphServiceClient::createWithRequestAdapter($requestAdapter); |
| 87 | + |
| 88 | +``` |
| 89 | + |
| 90 | +## Access token management |
| 91 | + |
| 92 | +Using the `TokenRequestContext`, an instance of the `GraphServiceClient` requests access tokens and refresh tokens. |
| 93 | +The tokens are stored by default in an in-memory cache so that future requests using the same instance of the `GraphServiceClient` can re-use the previously acquired tokens. |
| 94 | + |
| 95 | +The default in-memory cache is a map/dictionary with a unique key identifying a user/application with a tenant and a PHPLeague [`AccessToken`](https://github.com/thephpleague/oauth2-client/blob/master/src/Token/AccessToken.php) object as its value. The unique key ensures the right token for a user is retrieved from the cache. For `TokenRequestContexts` that do not require a signed-in user (application permissions), the cache key will be **`{tenantId}-{clientId}`** and for those that require a signed-in user (delegated permissions), the cache key will be |
| 96 | +**`{tenantId}-{clientId}-{userId}`**. The `AccessToken` object carries both the `access_token`, its expiry and a `refresh_token` if available. |
| 97 | +The in-memory cache lives as a PHP object within your application's PHP process and is destroyed when the process terminates. |
| 98 | + |
| 99 | +For scenarios where an application requires a signed-in user, retaining the same |
| 100 | +instance of the `GraphServiceClient` across multiple requests to your application for the same user's session is not feasible. This section outlines |
| 101 | +how your application can retrieve access tokens from the SDK and pass already acquired access tokens to the SDK for future requests without the user signing in for each request. |
| 102 | + |
| 103 | +### Retrieving the access token from the SDK |
| 104 | + |
| 105 | +The SDK provides a mechanism to expose the access token and refresh token that it acquires to your application for use in future requests. This would prevent the SDK from making a new |
| 106 | +token request with each `GraphServiceClient` your application instantiates. It also allows your application to prevent its users from signing in with each request within a session. |
| 107 | + |
| 108 | +By default, a `GraphServiceClient` instance caches access tokens in a built-in [`InMemoryAccessTokenCache`](https://github.com/microsoft/kiota-authentication-phpleague-php/blob/main/src/Cache/InMemoryAccessTokenCache.php). The cache will be populated with a PHPLeague [`AccessToken`](https://github.com/thephpleague/oauth2-client/blob/master/src/Token/AccessToken.php) object which carries both the `access_token`, its expiry and a `refresh_token` if available. When the `GraphServiceClient` instance is re-used for a request with the same user/application, the in-memory cache is checked for a valid token otherwise a new token request is made. |
| 109 | + |
| 110 | +However, to get the cached token that the SDK requests for a user/application you |
| 111 | +can initialise an `InMemoryAccessTokenCache` or pass a custom implementation of the [`AccessTokenCache`](https://github.com/microsoft/kiota-authentication-phpleague-php/blob/main/src/Cache/AccessTokenCache.php) interface and pass it as a parameter when initialising the `GraphServiceClient`. The two approaches are outlined below: |
| 112 | + |
| 113 | +### Using an InMemoryAccessTokenCache instance |
| 114 | + |
| 115 | +```php |
| 116 | +use Microsoft\Kiota\Authentication\Cache\InMemoryAccessTokenCache; |
| 117 | +use Microsoft\Graph\GraphServiceClient; |
| 118 | +use Microsoft\Graph\Core\Authentication\GraphPhpLeagueAccessTokenProvider; |
| 119 | +use Microsoft\Graph\Core\Authentication\GraphPhpLeagueAuthenticationProvider; |
| 120 | +use Microsoft\Kiota\Authentication\Oauth\AuthorizationCodeContext; |
| 121 | + |
| 122 | +$tokenRequestContext = new AuthorizationCodeContext( |
| 123 | + 'tenantId', |
| 124 | + 'clientId', |
| 125 | + 'clientSecret', |
| 126 | + 'authCode', |
| 127 | + 'redirectUri' |
| 128 | +); |
| 129 | +$scopes = ['User.Read', 'Mail.ReadWrite']; |
| 130 | + |
| 131 | +$inMemoryCache = new InMemoryAccessTokenCache(); |
| 132 | + |
| 133 | +$graphServiceClient = GraphServiceClient::createWithAuthenticationProvider( |
| 134 | + GraphPhpLeagueAuthenticationProvider::createWithAccessTokenProvider( |
| 135 | + GraphPhpLeagueAccessTokenProvider::createWithCache( |
| 136 | + $inMemoryCache, |
| 137 | + $tokenRequestContext, |
| 138 | + $scopes |
| 139 | + ) |
| 140 | + ) |
| 141 | +); |
| 142 | + |
| 143 | +$accessToken = $inMemoryCache->getTokenWithContext($tokenRequestContext); |
| 144 | + |
| 145 | +``` |
| 146 | + |
| 147 | +### Using a custom AccessTokenCache implementation |
| 148 | + |
| 149 | +A custom [`AccessTokenCache`](https://github.com/microsoft/kiota-authentication-phpleague-php/blob/main/src/Cache/AccessTokenCache.php) interface implementation can also be provided. After the request, the SDK persists the token in the |
| 150 | +custom cache via the `persistAccessToken()` method. |
| 151 | + |
| 152 | +By default, the SDK adds a unique cache key/identifier to a `TokenRequestContext` that uniquely identifies the tenant, client and user (if applicable). |
| 153 | +For `TokenRequestContexts` that do not require a signed-in user (application permissions), the cache key will be |
| 154 | +**`{tenantId}-{clientId}`** and for those that require a signed-in user (delegated permissions), the cache key will be |
| 155 | +**`{tenantId}-{clientId}-{userId}`**. |
| 156 | + |
| 157 | +Alternatively, you can override the default cache key |
| 158 | + |
| 159 | +To retrieve the access token persisted to your custom cache for a particular user's/application's `TokenRequestContext`: |
| 160 | +```php |
| 161 | + |
| 162 | +$accessToken = $customCache->getAccessToken($tokenRequestContext->getCacheKey()); |
| 163 | + |
| 164 | +``` |
| 165 | + |
| 166 | +### Initializing a GraphServiceClient with an access token |
| 167 | + |
| 168 | +For applications that already have built-in mechanisms to fetch and refresh access tokens, the SDK supports passing these tokens to a `GraphServiceClient` by initializing |
| 169 | +a client using an [`AccessTokenCache`](https://github.com/microsoft/kiota-authentication-phpleague-php/blob/main/src/Cache/AccessTokenCache.php) interface implementation. |
| 170 | + |
| 171 | +The SDK provides a built-in implementation of this interface via an [`InMemoryAccessTokenCache`](https://github.com/microsoft/kiota-authentication-phpleague-php/blob/main/src/Cache/InMemoryAccessTokenCache.php). |
| 172 | + |
| 173 | +This is also useful when re-using a previously retrieved access token for a signed-in user during a previous request. |
| 174 | + |
| 175 | +The SDK will check the cache for a valid token before considering requesting a new token. If the provided token is expired |
| 176 | +and a refresh token is present, the access token will be refreshed and persisted to the cache. If no refresh token is provided, the SDK requests attempts to retrieve a new access token and persists it to the cache. In cases where a signed-in user is present, e.g. authorization_code OAuth flows, the new token request will most likely fail because no valid `authorization_code` will be present meaning the user has to sign in again. |
| 177 | + |
| 178 | +### Using the `InMemoryAccessTokenCache` |
| 179 | + |
| 180 | +The in-memory cache can be hydrated/initialised using the `TokenRequestContext` and a PHPLeague [`AccessToken`](https://github.com/thephpleague/oauth2-client/blob/master/src/Token/AccessToken.php) object for a user/application: |
| 181 | + |
| 182 | +```php |
| 183 | + |
| 184 | +use Microsoft\Kiota\Authentication\Cache\InMemoryAccessTokenCache; |
| 185 | +use Microsoft\Graph\GraphServiceClient; |
| 186 | +use Microsoft\Graph\Core\Authentication\GraphPhpLeagueAccessTokenProvider; |
| 187 | +use Microsoft\Graph\Core\Authentication\GraphPhpLeagueAuthenticationProvider; |
| 188 | +use League\OAuth2\Client\Token\AccessToken; |
| 189 | + |
| 190 | +$tokenRequestContext = new AuthorizationCodeContext( |
| 191 | + 'tenantId', |
| 192 | + 'clientId', |
| 193 | + 'clientSecret', |
| 194 | + 'authCode', // use a placeholder value since user is not signed in again |
| 195 | + 'redirectUri' |
| 196 | +); |
| 197 | + |
| 198 | +$cache = new InMemoryAccessTokenCache( |
| 199 | + $tokenRequestContext, |
| 200 | + new AccessToken( |
| 201 | + [ |
| 202 | + 'access_token' => $accessToken, |
| 203 | + 'refresh_token' => $refreshToken, |
| 204 | + 'expires' => 1 |
| 205 | + ] |
| 206 | + ) |
| 207 | +); |
| 208 | + |
| 209 | +$graphServiceClient = GraphServiceClient::createWithAuthenticationProvider( |
| 210 | + GraphPhpLeagueAuthenticationProvider::createWithAccessTokenProvider( |
| 211 | + GraphPhpLeagueAccessTokenProvider::createWithCache( |
| 212 | + $cache, |
| 213 | + $tokenRequestContext, |
| 214 | + $scopes |
| 215 | + ) |
| 216 | + ) |
| 217 | +); |
| 218 | + |
| 219 | +``` |
| 220 | + |
| 221 | +For scenarios where your application may need to make requests for multiple users using the same `GraphServiceClient`, the `InMemoryAccessTokenCache` can |
| 222 | +be initialized with multiple TokenRequestContext-AccessToken pairs using `withToken`: |
| 223 | +```php |
| 224 | + |
| 225 | +use Microsoft\Kiota\Authentication\Cache\InMemoryAccessTokenCache; |
| 226 | +use Microsoft\Graph\GraphServiceClient; |
| 227 | +use Microsoft\Graph\Core\Authentication\GraphPhpLeagueAccessTokenProvider; |
| 228 | +use Microsoft\Graph\Core\Authentication\GraphPhpLeagueAuthenticationProvider; |
| 229 | +use League\OAuth2\Client\Token\AccessToken; |
| 230 | + |
| 231 | +$tokenRequestContext = new AuthorizationCodeContext( |
| 232 | + 'tenantId', |
| 233 | + 'clientId', |
| 234 | + 'clientSecret', |
| 235 | + 'authCode', // use a placeholder value since user is not signed in again |
| 236 | + 'redirectUri' |
| 237 | +); |
| 238 | + |
| 239 | +$cache = (new InMemoryAccessTokenCache($tokenRequestContext, new AccessToken([ |
| 240 | + // ... |
| 241 | +]))); |
| 242 | + |
| 243 | +$cache->withToken($tokenRequestContext2, new AccessToken([ |
| 244 | + // ... |
| 245 | + ]))->withToken($tokenRequestContext, new AccessToken([ |
| 246 | + // ... |
| 247 | + ]))->withToken($tokenRequestContext3, new AccessToken()); |
| 248 | + |
| 249 | + |
| 250 | +$graphServiceClient = GraphServiceClient::createWithAuthenticationProvider( |
| 251 | + GraphPhpLeagueAuthenticationProvider::createWithAccessTokenProvider( |
| 252 | + GraphPhpLeagueAccessTokenProvider::createWithCache( |
| 253 | + $cache, |
| 254 | + $tokenRequestContext, |
| 255 | + $scopes |
| 256 | + ) |
| 257 | + ) |
| 258 | +); |
| 259 | + |
| 260 | +``` |
| 261 | + |
| 262 | +### Using a custom `AccessTokenCache` implementation` |
| 263 | + |
| 264 | +The SDK retrieves cached tokens using a cache key/identifier on the `TokenRequestContext`. The cache key |
| 265 | +on the `TokenRequestContext` is set using `setCacheKey()` which accepts an [`AccessToken`](https://github.com/thephpleague/oauth2-client/blob/master/src/Token/AccessToken.php) object. |
| 266 | + |
| 267 | +The `TokenRequestContext` uses the `AccessToken` to generate a unique identifier per user, client and tenant. For `TokenRequestContexts` that do not require a signed-in user (application permissions), the cache key will be |
| 268 | +**`{tenantId}-{clientId}`** and for those that require a signed-in user (delegated permissions), the cache key will be |
| 269 | +**`{tenantId}-{clientId}-{userId}`**. |
| 270 | + |
| 271 | +For this scenario, the custom AccessTokenCache will need to be initialized in a way that the cache key set on the |
| 272 | +`TokenRequestContext` aligns with the key the custom AccessTokenCache maps to the user/application's access token |
| 273 | + |
| 274 | +```php |
| 275 | + |
| 276 | +$accessToken = new AccessToken([ |
| 277 | + 'access_token' => $accessToken, |
| 278 | + 'refresh_token' => $refreshToken, |
| 279 | + 'expires' => ... |
| 280 | +]); |
| 281 | + |
| 282 | +$tokenRequestContext->setCacheKey($accessToken); |
| 283 | + |
| 284 | +// init custom cache with tokens mapped to specific user/app using $tokenRequestContext->getCacheKey() |
| 285 | +$customCache = new CustomCache($tokenRequestContext->getCacheKey(), $accessToken); |
| 286 | + |
| 287 | +// init graph client |
| 288 | +$graphServiceClient = GraphServiceClient::createWithAuthenticationProvider( |
| 289 | + GraphPhpLeagueAuthenticationProvider::createWithAccessTokenProvider( |
| 290 | + GraphPhpLeagueAccessTokenProvider::createWithCache( |
| 291 | + $customCache, |
| 292 | + $tokenRequestContext, |
| 293 | + $scopes |
| 294 | + ) |
| 295 | + ) |
| 296 | +); |
| 297 | + |
| 298 | +``` |
0 commit comments