OAuth 2.0 Client

repository·master·Indexed 26 days ago

https://github.com/thephpleague/oauth2-client

A PHP library providing a standardized foundation for integrating with OAuth 2.0 service providers according to RFC 6749. It includes a GenericProvider for Bearer token providers, support for Authorization Code, Client Credentials, and Password grants, and PKCE. The library supports PHP 7.1 through 8.5 and offers official provider clients for Facebook, GitHub, Google, Instagram, and LinkedIn.

Tokens
4.5K
Snippets
10
Records
34
Agent score
83%

What's inside league/oauth2-client

  1. Implement a custom Provider Client

    master

    To implement a new OAuth 2.0 service provider, extend League\OAuth2\Client\Provider\AbstractProvider and implement the following required abstract methods:

    • getBaseAuthorizationUrl()
    • getBaseAccessTokenUrl(array $params)
    • getResourceOwnerDetailsUrl(AccessToken $token)
    • protected function getDefaultScopes()
    • protected function checkResponse(ResponseInterface $response, $data)
    • protected function createResourceOwner(array $response, AccessToken $token)

    If your provider requires the access token to be sent via headers, you should also override:

    • protected function getAuthorizationHeaders($token = null)

    Naming Convention Tip: When creating a new package, do not use the league vendor prefix. Instead, use your own username and prepend oauth2- to the package name (e.g., yourname/oauth2-service).

    public function getBaseAuthorizationUrl();
    public function getBaseAccessTokenUrl(array $params);
    public function getResourceOwnerDetailsUrl(AccessToken $token);
    protected function getDefaultScopes();
    protected function checkResponse(ResponseInterface $response, $data);
    protected function createResourceOwner(array $response, AccessToken $token);
  2. Enable PKCE for Authorization Code Grant

    master

    To use Proof Key for Code Exchange (PKCE), set the pkceMethod option in your provider configuration.

    Supported methods:

    • S256: Recommended. Uses SHA256 hashing.
    • plain: Not recommended. Sends the challenge as plain text.

    You must store the PKCE code in a session after calling getAuthorizationUrl() and restore it using setPkceCode() before calling getAccessToken().

  3. Use Resource Owner Password Credentials Grant

    master

    This grant type allows exchanging a user's username and password directly for an access token.

    Warning: This is considered a security anti-pattern. Only use this if the service provider supports it and there is a high degree of trust between the client and the resource owner. It is recommended to use the Authorization Code grant instead.

    try {
        $accessToken = $provider->getAccessToken('password', [
            'username' => 'myuser',
            'password' => 'mysupersecretpassword'
        ]);
    } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
        exit($e->getMessage());
    }
  4. Implement Authorization Code Grant

    master

    The Authorization Code grant is the most common method for authenticating users with a third-party service. Using the GenericProvider, you must:

    1. Redirect the user to the authorization URL generated by getAuthorizationUrl().
    2. Store the generated state in a session to prevent CSRF attacks.
    3. After redirection, verify the returned state matches the stored one.
    4. Exchange the code for an access token using getAccessToken('authorization_code', ['code' => $_GET['code']]).
    5. Use the token to fetch resource owner details via getResourceOwner() or create authenticated requests via getAuthenticatedRequest().
    $provider = new \League\OAuth2\Client\Provider\GenericProvider([
        'clientId'                => 'XXXXXX',
        'clientSecret'            => 'XXXXXX',
        'redirectUri'             => 'https://my.example.com/your-redirect-url/',
        'urlAuthorize'            => 'https://service.example.com/authorize',
        'urlAccessToken'          => 'https://service.example.com/token',
        'urlResourceOwnerDetails' => 'https://service.example.com/resource'
    ]);
    
    session_start();
    
    if (!isset($_GET['code'])) {
        $authorizationUrl = $provider->getAuthorizationUrl();
        $_SESSION['oauth2state'] = $provider->getState();
        header('Location: ' . $authorizationUrl);
        exit;
    } elseif (empty($_GET['state']) || empty($_SESSION['oauth2state']) || $_GET['state'] !== $_SESSION['oauth2state']) {
        if (isset($_SESSION['oauth2state'])) {
            unset($_SESSION['oauth2state']);
        }
        exit('Invalid state');
    } else {
        try {
            $tokens = $provider->getAccessToken('authorization_code', [
                'code' => $_GET['code']
            ]);
    
            $resourceOwner = $provider->getResourceOwner($tokens);
            $request = $provider->getAuthenticatedRequest(
                'GET',
                'https://service.example.com/resource',
                $tokens
            );
        } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
            exit($e->getMessage());
        }
    }
  5. Install league/oauth2-client via Composer

    master

    You can install the base OAuth 2.0 client package using Composer. This package provides the interfaces and abstract classes necessary to build OAuth 2.0 clients, as well as a GenericProvider class that works with many providers using Bearer tokens.

    Note: Before installing this base package, check if an official or third-party provider client already exists for your specific service to avoid manual configuration.

    $ composer require league/oauth2-client
  6. Install official OAuth 2.0 provider clients

    master

    The League OAuth2 Client ecosystem provides official provider-specific packages for common gateways. You can install these using Composer by requiring the specific package name for your provider.

    Available official packages include:

    • Facebook: league/oauth2-facebook
    • Github: league/oauth2-github
    • Google: league/oauth2-google
    • Instagram: league/oauth2-instagram
    • LinkedIn: league/oauth2-linkedin
    $ composer require league/<package-name>
  7. Refresh an expired access token

    master

    If an access token has expired, you can request a new one using a refresh token without requiring user interaction. Use the refresh_token grant type with the getAccessToken method.

    if ($existingAccessToken->hasExpired()) {
        $tokens = $provider->getAccessToken('refresh_token', [
            'refresh_token' => $existingRefreshToken
        ]);
    
        // Store new tokens
        saveNewAccessTokenToYourDataStore($tokens->getToken());
        saveNewRefreshTokenToYourDataStore($tokens->getRefreshToken());
    }
  8. Use Client Credentials Grant

    master

    Use the client_credentials grant type when your application needs to act on its own behalf to access resources it owns, rather than acting on behalf of a specific user. This uses only the clientId and clientSecret.

    try {
        $accessToken = $provider->getAccessToken('client_credentials');
    } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
        exit($e->getMessage());
    }