creatorshub/oauth2-creatorshub

CreatorsHub OAuth 2.0 Client Provider for The PHP League OAuth2-Client

v1.1 2018-07-03 20:21 UTC

This package is auto-updated.

Last update: 2024-10-29 04:59:02 UTC


README

This package provides CreatorsHub OAuth 2.0 support for the PHP League's OAuth 2.0 Client.

This package is compliant with PSR-1, PSR-2 and PSR-4. If you notice compliance oversights, please send a patch via pull request.

Requirements

The following versions of PHP are supported.

  • PHP 7.0
  • PHP 7.1
  • HHVM

Installation

To install, use composer:

composer require creatorshub/oauth2-creatorshub

Usage

Authorization Code Flow

$provider = new CreatorsHub\OAuth2\Client\Provider\CreatorsHub([
    'clientId'     => '{creatorshub-client-id}',
    'clientSecret' => '{creatorshub-client-secret}',
    'redirectUri'  => 'https://example.com/callback-url'
]);

// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {

    // Fetch the authorization URL from the provider; this returns the
    // urlAuthorize option and generates and applies any necessary parameters
    // (e.g. state).
    $authorizationUrl = $provider->getAuthorizationUrl();

    // Get the state generated for you and store it to the session.
    $_SESSION['oauth2state'] = $provider->getState();

    // Redirect the user to the authorization URL.
    header('Location: ' . $authorizationUrl);
    exit;

// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) {

    if (isset($_SESSION['oauth2state'])) {
        unset($_SESSION['oauth2state']);
    }
    
    exit('Invalid state');

} else {

    try {

        // Try to get an access token using the authorization code grant.
        $accessToken = $provider->getAccessToken('authorization_code', [
            'code' => $_GET['code']
        ]);

        // We have an access token, which we may use in authenticated
        // requests against the service provider's API.
        echo 'Access Token: ' . $accessToken->getToken() . "<br>";
        echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "<br>";
        echo 'Expired in: ' . $accessToken->getExpires() . "<br>";
        echo 'Already expired? ' . ($accessToken->hasExpired() ? 'expired' : 'not expired') . "<br>";

        // Using the access token, we may look up details about the
        // resource owner.
        $resourceOwner = $provider->getResourceOwner($accessToken);

        var_export($resourceOwner->toArray());

    } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {

        // Failed to get the access token or user details.
        exit($e->getMessage());

    }

}

Refreshing a Token

Refresh tokens are only provided to applications which request offline access. You can specify offline access by setting the accessType option in your provider:

$provider = new CreatorsHub\OAuth2\Client\Provider\CreatorsHub([
    'clientId'     => '{creatorshub-client-id}',
    'clientSecret' => '{creatorshub-client-secret}',
    'redirectUri'  => 'https://example.com/callback-url',
    'accessType'   => 'offline',
]);

It is important to note that the refresh token is only returned on the first request after this it will be null. You should securely store the refresh token when it is returned:

$token = $provider->getAccessToken('authorization_code', [
    'code' => $code
]);

// persist the token in a database
$refreshToken = $token->getRefreshToken();

If you ever need to get a new refresh token you can request one by forcing the approval prompt:

$authUrl = $provider->getAuthorizationUrl(['approval_prompt' => 'force']);

Now you have everything you need to refresh an access token using a refresh token:

$provider = new CreatorsHub\OAuth2\Client\Provider\CreatorsHub([
    'clientId'     => '{creatorshub-app-id}',
    'clientSecret' => '{creatorshub-app-secret}',
    'redirectUri'  => 'https://example.com/callback-url',
]);

$grant = new League\OAuth2\Client\Grant\RefreshToken();
$token = $provider->getAccessToken($grant, ['refresh_token' => $refreshToken]);

Scopes

If needed, you can include an array of scopes when getting the authorization url. Example:

$authorizationUrl = $provider->getAuthorizationUrl([
    'scope' => [
        'some scope',
        'another scope',
    ]
]);
header('Location: ' . $authorizationUrl);
exit;

Testing

$ ./vendor/bin/phpunit

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.