PHP code example of aptenex / oauth2-client-middleware

1. Go to this page and download the library: Download aptenex/oauth2-client-middleware library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

aptenex / oauth2-client-middleware example snippets


use Somoza\OAuth2Middleware\OAuth2Middleware;
use Somoza\OAuth2Middleware\TokenService\Bearer;

$stack = new \GuzzleHttp\HandlerStack();
$stack->setHandler(new CurlHandler());
$client = new \GuzzleHttp\Client(['handler' => $stack]);

// instantiate a provider, see league/oauth2-client docs
$provider = new GenericProvider(
    [
        'clientId' => 'your_client_id',
        'clientSecret' => 'your_client_secret',
        'urlAuthorize' => 'your_authorization_url',
        'urlAccessToken' => 'your_access_token_url',
        'urlResourceOwnerDetails' => 'your_resource_owner_url', 
    ], 
    [ 'httpClient' => $client ] // or don't pass it and let the oauth2-client create its own Guzzle client
);

// attach our oauth2 middleware
$bearerMiddleware = new OAuth2Middleware(
    new Bearer($provider), // use the Bearer token type
    [ // ignore (do not attempt to authorize) the following URLs
        $provider->getBaseAuthorizationUrl(),
        $provider->getBaseAccessTokenUrl(),
    ]
);
$stack->push($bearerMiddleware);

// if you want to debug, it might be useful to attach a PSR7 logger here

use Somoza\OAuth2Middleware\OAuth2Middleware;
use Somoza\OAuth2Middleware\TokenService\Bearer;
use League\OAuth2\Client\Token\AccessToken;

// see previous example for initialization
$tokenStore = new EncryptedCache(); // you can use whatever you want here
$token = null;
if ($tokenStore->contains($userId)) {
    $tokenData = json_decode($cache->fetch($userId));
    $token = new AccessToken($tokenData);
}

$bearerMiddleware = new OAuth2Middleware(
    new Bearer(
        $provider, // defined as in the "Usage" example
        $token, 
        function (AccessToken $newToken, AccessToken $oldToken) 
          use ($tokenStore, $userId) {
            // called whenever a new AccessToken is fetched
            $tokenStore->save($userId, $newToken->jsonSerialize());
        }
    ), 
);

$stack->push($bearerMiddleware);