### Install Bundler Source: https://github.com/thephpleague/oauth2-client/blob/master/docs/README.md Installs the project's dependencies using Bundler. Follow any specific bundler version instructions if prompted. ```shell bundle install ``` -------------------------------- ### Complete GenericProvider Configuration Example Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/configuration.md This example demonstrates how to instantiate the GenericProvider with all required and several optional configuration parameters. It includes settings for client credentials, redirect URI, endpoint URLs, provider-specific options, and Guzzle HTTP client configurations. ```php $provider = new \League\OAuth2\Client\Provider\GenericProvider([ // Required 'clientId' => '550e8400-e29b-41d4-a716-446655440000', 'clientSecret' => 'your-secret-key-here', 'redirectUri' => 'https://myapp.example.com/auth/callback', 'urlAuthorize' => 'https://oauth.service.com/oauth/authorize', 'urlAccessToken' => 'https://oauth.service.com/oauth/token', 'urlResourceOwnerDetails' => 'https://api.service.com/v1/user', // Optional provider settings 'accessTokenMethod' => 'POST', 'accessTokenResourceOwnerId' => 'user_id', 'scopeSeparator' => ' ', 'responseError' => 'error', 'responseCode' => 'error_code', 'responseResourceOwnerId' => 'uid', 'scopes' => ['profile', 'email', 'openid'], 'pkceMethod' => 'S256', // Guzzle options 'timeout' => 10, 'proxy' => 'http://proxy.corporate.com:8080', ]); ``` -------------------------------- ### Install Third-Party Provider Client Source: https://github.com/thephpleague/oauth2-client/blob/master/docs/providers/thirdparty.md Use Composer to install a third-party OAuth2 provider client package. Replace `[vendor/package-name]` with the actual package name. ```bash $ composer require [vendor/package-name] ``` -------------------------------- ### Install rbenv using Homebrew Source: https://github.com/thephpleague/oauth2-client/blob/master/docs/README.md Installs the rbenv version manager using the Homebrew package manager. Ensure Homebrew is installed first. ```shell brew install rbenv ``` -------------------------------- ### Install rbenv Source: https://github.com/thephpleague/oauth2-client/blob/master/docs/README.md Installs the rbenv version manager. This command assumes rbenv has been added to your PATH. ```shell rbenv install ``` -------------------------------- ### Resource Owner Response Examples Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-resource-owner.md These examples show different response formats for resource owner details from various providers. The `responseResourceOwnerId` option must be set to match the key containing the unique user identifier in the response. ```php // GitHub-style response [ 'id' => 12345, 'login' => 'johndoe', 'name' => 'John Doe', 'email' => 'john@github.com' ] // Use: 'responseResourceOwnerId' => 'id' ``` ```php // Custom provider [ 'user_id' => 'abc123', 'username' => 'johndoe', 'full_name' => 'John Doe' ] // Use: 'responseResourceOwnerId' => 'user_id' ``` ```php // Google Oauth 2.0 [ 'sub' => '1234567890', 'email' => 'john@example.com', 'email_verified' => true, 'name' => 'John Doe' ] // Use: 'responseResourceOwnerId' => 'sub' ``` -------------------------------- ### Usage Example: GenericProvider with HttpBasicAuthOptionProvider Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-option-providers.md Demonstrates how to configure and use the GenericProvider with HttpBasicAuthOptionProvider for token requests that utilize HTTP Basic Authentication. ```php $provider = new \League\OAuth2\Client\Provider\GenericProvider( [ 'clientId' => 'your-client-id', 'clientSecret' => 'your-client-secret', 'redirectUri' => 'https://example.com/callback', 'urlAuthorize' => 'https://provider.com/authorize', 'urlAccessToken' => 'https://provider.com/token', 'urlResourceOwnerDetails' => 'https://api.provider.com/user', ], [ 'optionProvider' => new \League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider() ] ); // Token request will use HTTP Basic Auth $token = $provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]); ``` -------------------------------- ### Instantiate GenericProvider with Comprehensive Options Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-generic-provider.md Use this example to configure the GenericProvider with all required and many optional parameters, including HTTP client settings. Ensure all required options are provided for successful instantiation. ```php $provider = new \League\OAuth2\Client\Provider\GenericProvider([ // Required 'clientId' => 'abc123def456', 'clientSecret' => 'secret123', 'redirectUri' => 'https://myapp.example.com/auth/callback', 'urlAuthorize' => 'https://oauth.service.com/oauth/authorize', 'urlAccessToken' => 'https://oauth.service.com/oauth/token', 'urlResourceOwnerDetails' => 'https://api.service.com/v1/user', // Optional 'accessTokenMethod' => 'POST', 'accessTokenResourceOwnerId' => 'user_id', 'scopeSeparator' => ' ', 'responseError' => 'error', 'responseCode' => 'error_code', 'responseResourceOwnerId' => 'uid', 'scopes' => ['profile', 'email'], 'pkceMethod' => 'S256', // HTTP Client options 'timeout' => 10, ]); ``` -------------------------------- ### HttpBasicAuthOptionProvider Usage Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-option-providers.md This example demonstrates how to instantiate and use the HttpBasicAuthOptionProvider with a GenericProvider. When used, token requests will automatically include the client credentials in the HTTP Basic Authorization header. ```APIDOC ## HttpBasicAuthOptionProvider ### Description Implements HTTP Basic Authentication for client credentials (RFC 6749 ยง2.3.1). Client ID and secret are sent as an HTTP Basic Authorization header instead of in the request body. ### Constructor No constructor parameters. Typically injected via collaborators. ### Request Format Example For a token request using HTTP Basic Auth: ``` POST /token HTTP/1.1 Authorization: Basic YWJjMTIzOnNlY3JldA== Content-Type: application/x-www-form-urlencoded code=auth_code&redirect_uri=...&grant_type=authorization_code ``` The `Authorization` header is base64-encoded `clientId:clientSecret`. ### Validation Throws `InvalidArgumentException` if either `client_id` or `client_secret` is empty/missing in the parameters. ### Usage Example ```php $provider = new \League\OAuth2\Client\Provider\GenericProvider([ 'clientId' => 'your-client-id', 'clientSecret' => 'your-client-secret', 'redirectUri' => 'https://example.com/callback', 'urlAuthorize' => 'https://provider.com/authorize', 'urlAccessToken' => 'https://provider.com/token', 'urlResourceOwnerDetails' => 'https://api.provider.com/user', ], [ 'optionProvider' => new \League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider() ]); // Token request will use HTTP Basic Auth $token = $provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]); ``` ``` -------------------------------- ### Install League OAuth2 Client Source: https://github.com/thephpleague/oauth2-client/blob/master/docs/index.md Use Composer to require the base OAuth2 client package. This is necessary if you plan to use the GenericProvider or build your own custom provider. If using an existing provider client, you may not need to require this package directly. ```bash composer require league/oauth2-client ``` -------------------------------- ### setHttpClient / getHttpClient Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-abstract-provider.md Set or get the HTTP client (Guzzle) instance. ```APIDOC ## setHttpClient / getHttpClient ### Description Set or get the HTTP client (Guzzle) instance. ### Methods - `setHttpClient(HttpClientInterface $client): self` - `getHttpClient(): HttpClientInterface` ``` -------------------------------- ### Get Token as String Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/README.md Retrieve the access token as a plain string for display or logging purposes. ```php // Get the token as string echo "Token: " . $token->getToken(); ``` -------------------------------- ### AccessToken Serialization and Deserialization Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-access-token.md Provides an example of how to serialize an AccessToken object to JSON for storage (e.g., in a session) and how to deserialize it back into an AccessToken object. ```APIDOC ## Serialization Example ### Description Demonstrates saving an AccessToken to a session and restoring it. ### Usage Example ```php // Save to session $_SESSION['oauth_token'] = json_encode($token); // Restore from session $tokenData = json_decode($_SESSION['oauth_token'], true); $restoredToken = new AccessToken($tokenData); ``` ``` -------------------------------- ### POST Request Format Example Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-option-providers.md Shows the typical HTTP POST request format for a token request using URL-encoded form data in the body, as handled by the PostAuthOptionProvider. ```http POST /token HTTP/1.1 Content-Type: application/x-www-form-urlencoded client_id=abc123&client_secret=secret&code=auth_code&redirect_uri=...&grant_type=authorization_code ``` -------------------------------- ### Implement CustomAuthOptionProvider Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-option-providers.md Implement the OptionProviderInterface to create a custom option provider for unique authentication schemes. This example demonstrates adding a custom header with a HMAC-SHA256 signature. ```php namespace MyApp; use League\OAuth2\Client\OptionProvider\OptionProviderInterface; class CustomAuthOptionProvider implements OptionProviderInterface { public function getAccessTokenOptions($method, array $params) { $options = [ 'headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded', 'X-Custom-Auth' => hash_hmac('sha256', $params['client_id'], $params['client_secret']) ] ]; if ($method === 'POST') { $options['body'] = http_build_query($params, '', '&', \PHP_QUERY_RFC3986); } return $options; } } // Usage $provider = new GenericProvider( [/* ... config ... */], ['optionProvider' => new CustomAuthOptionProvider()] ); ``` -------------------------------- ### setOptionProvider / getOptionProvider Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-abstract-provider.md Set or get the option provider for customizing request options. ```APIDOC ## setOptionProvider / getOptionProvider ### Description Set or get the option provider for customizing request options. ### Methods - `setOptionProvider(OptionProviderInterface $provider): self` - `getOptionProvider(): OptionProviderInterface` ``` -------------------------------- ### Configure Generic OpenID Connect Provider Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/configuration.md A general configuration for OpenID Connect providers. This example uses 'sub' as the resource owner ID and specifies common scopes like 'openid', 'profile', and 'email'. ```php $provider = new GenericProvider([ 'clientId' => 'your-client-id', 'clientSecret' => 'your-client-secret', 'redirectUri' => 'https://myapp.example.com/auth/callback', 'urlAuthorize' => 'https://provider.example.com/oauth/authorize', 'urlAccessToken' => 'https://provider.example.com/oauth/token', 'urlResourceOwnerDetails' => 'https://provider.example.com/oauth/userinfo', 'responseResourceOwnerId' => 'sub', 'scopeSeparator' => ' ', 'scopes' => ['openid', 'profile', 'email'], 'pkceMethod' => 'S256' ]); ``` -------------------------------- ### Get PKCE Code Verifier Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-abstract-provider.md Retrieves the current PKCE code verifier. Use this to check if PKCE is enabled for the provider. ```php public function getPkceCode(): string|null ``` ```php $code = $provider->getPkceCode(); if ($code) { echo "PKCE enabled for this provider"; } ``` -------------------------------- ### Get Access Token String Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-access-token.md Retrieves the access token string. Use this when you need the raw token value. ```php public function getToken(): string ``` ```php $token = new AccessToken(['access_token' => 'xyz']); echo $token->getToken(); // 'xyz' ``` -------------------------------- ### Initiate Authorization Flow Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-abstract-provider.md Starts the OAuth authorization process. By default, it sends an HTTP redirect. A custom handler can be provided to manage the redirect logic. ```php // Default behavior with HTTP redirect $provider->authorize(); // Custom redirect handler $provider->authorize([], function($url, $provider) { return ['redirect_url' => $url]; }); ``` -------------------------------- ### Set/Get Request Factory Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-abstract-provider.md Set or get the request factory instance. This factory is responsible for creating HTTP requests. ```php public function setRequestFactory(RequestFactory $factory): self public function getRequestFactory(): RequestFactory ``` -------------------------------- ### Set/Get HTTP Client Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-abstract-provider.md Set or get the HTTP client instance, typically Guzzle. This client handles all outgoing HTTP communications. ```php public function setHttpClient(HttpClientInterface $client): self public function getHttpClient(): HttpClientInterface ``` -------------------------------- ### GenericProvider Core Methods Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/INDEX.md Details on the GenericProvider class, a standard implementation for any RFC 6749 compliant OAuth 2.0 server. It covers configuration, bearer token authentication, and authorization flow examples. Key methods include getBaseAuthorizationUrl, getBaseAccessTokenUrl, getResourceOwnerDetailsUrl, and getDefaultScopes. ```APIDOC ## GenericProvider ### Description Implements a generic OAuth 2.0 provider compatible with any RFC 6749 compliant server. ### Key Methods - **getBaseAuthorizationUrl()**: Returns the base URL for authorization requests. - **getBaseAccessTokenUrl()**: Returns the base URL for access token requests. - **getResourceOwnerDetailsUrl(AccessToken $token)**: Returns the URL to fetch resource owner details. - **getDefaultScopes()**: Returns the default scopes supported by the provider. ``` -------------------------------- ### Authorization Code Grant Flow Example Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-grants.md Demonstrates the standard OAuth 2.0 authorization code flow. This includes redirecting the user to the provider and exchanging the authorization code for an access token. ```php $provider = new GenericProvider([...]); // Step 1: Redirect user to authorization URL $authUrl = $provider->getAuthorizationUrl([ 'scope' => ['user:email'] ]); header('Location: ' . $authUrl); exit; // Step 2: Handle callback with authorization code $grant = new League\OAuth2\Client\Grant\AuthorizationCode(); $token = $provider->getAccessToken($grant, [ 'code' => $_GET['code'] ]); // Or use string for convenience $token = $provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]); ``` -------------------------------- ### Token Request with HTTP Basic Auth Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-option-providers.md Example of a token request using HTTP Basic Authentication. The Authorization header is base64-encoded client_id:client_secret. ```http POST /token HTTP/1.1 Authorization: Basic YWJjMTIzOnNlY3JldA== Content-Type: application/x-www-form-urlencoded code=auth_code&redirect_uri=...&grant_type=authorization_code ``` -------------------------------- ### Custom Grant Implementation Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-grants.md Provides a guide on how to create and register a custom OAuth 2.0 grant type with the client, including defining the grant name and required parameters. ```APIDOC ## Custom Grant Implementation To create a custom grant type: ```php namespace MyApp\Grant; use League\OAuth2\Client\Grant\AbstractGrant; class CustomGrant extends AbstractGrant { protected function getName() { return 'custom_flow'; } protected function getRequiredRequestParameters() { return ['custom_param']; } } // Usage: $factory = $provider->getGrantFactory(); $factory->setGrant('custom_flow', new CustomGrant()); $token = $provider->getAccessToken('custom_flow', ['custom_param' => 'value']); ``` ``` -------------------------------- ### Get Resource Owner Details URL Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-abstract-provider.md Abstract method that must be implemented by subclasses to return the resource owner details endpoint URL. ```php abstract public function getResourceOwnerDetailsUrl(AccessToken $token): string ``` -------------------------------- ### Handle Different OAuth Errors in PHP Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-exceptions.md This example demonstrates how to handle various OAuth 2.0 error responses by inspecting the error type within the `IdentityProviderException`'s response body. It includes specific logic for 'invalid_grant', 'invalid_client', and 'access_denied' errors, with a default fallback for other errors. ```php try { $token = $provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]); } catch ( League OAuth2 Client Provider Exception IdentityProviderException $e ) { $response = $e->getResponseBody(); // Handle based on error type if (is_array($response)) { switch ($response['error'] ?? null) { case 'invalid_grant': // Authorization code expired, restart flow header('Location: ' . $provider->getAuthorizationUrl()); break; case 'invalid_client': // Wrong credentials, check configuration error_log("OAuth client error: " . $e->getMessage()); header('HTTP/1.0 500 Server Error'); break; case 'access_denied': // User denied, inform them echo "You denied access to your account."; break; default: error_log("OAuth error: " . json_encode($response)); echo "Authorization failed. Please try again."; } } exit; } ``` -------------------------------- ### Retrieve an OAuth2 Grant Instance Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-grants.md Use this method to get a grant singleton by its registered name. Default grants are automatically registered upon first access. ```php $factory = $provider->getGrantFactory(); $grant = $factory->getGrant('authorization_code'); ``` -------------------------------- ### Initializing GenericProvider with Default Option Provider Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-option-providers.md Demonstrates how to initialize the GenericProvider, which uses the PostAuthOptionProvider by default to send client credentials and parameters in the POST request body. ```php $provider = new \League \OAuth2 \Client \Provider \GenericProvider([ 'clientId' => '...', 'clientSecret' => '...', 'redirectUri' => '...', 'urlAuthorize' => '...', 'urlAccessToken' => '...', 'urlResourceOwnerDetails' => '...', ]); // Internally uses PostAuthOptionProvider by default ``` -------------------------------- ### setRequestFactory / getRequestFactory Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-abstract-provider.md Set or get the request factory instance. ```APIDOC ## setRequestFactory / getRequestFactory ### Description Set or get the request factory instance. ### Methods - `setRequestFactory(RequestFactory $factory): self` - `getRequestFactory(): RequestFactory` ``` -------------------------------- ### Instantiate GenericProvider Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-generic-provider.md Instantiate the GenericProvider with required configuration options. Ensure all necessary parameters like clientId, clientSecret, redirectUri, and endpoint URLs are provided. ```php 'your-client-id', 'clientSecret' => 'your-client-secret', 'redirectUri' => 'https://example.com/oauth/callback', 'urlAuthorize' => 'https://oauth.example.com/authorize', 'urlAccessToken' => 'https://oauth.example.com/token', 'urlResourceOwnerDetails' => 'https://api.example.com/user', ]); ``` -------------------------------- ### Constructor Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-abstract-provider.md Initializes the AbstractProvider with configuration options and collaborators. It sets up the necessary components for interacting with an OAuth 2.0 authorization server. ```APIDOC ## Constructor ### Description Initializes the AbstractProvider with configuration options and collaborators. It sets up the necessary components for interacting with an OAuth 2.0 authorization server. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature ```php public function __construct(array $options = [], array $collaborators = []) ``` ### Parameters #### options (array) - Optional - Configuration options including `clientId`, `clientSecret`, `redirectUri`, `state`. Individual providers may introduce additional options. #### collaborators (array) - Optional - Dependency injection array. Keys: `grantFactory`, `requestFactory`, `httpClient`, `optionProvider`. ### Throws `InvalidArgumentException` if required options are missing (implementation-dependent). ### Usage Example ```php $provider = new League\OAuth2\Client\Provider\GenericProvider([ 'clientId' => 'your-client-id', 'clientSecret' => 'your-client-secret', 'redirectUri' => 'https://example.com/callback', 'urlAuthorize' => 'https://oauth.provider.com/authorize', 'urlAccessToken' => 'https://oauth.provider.com/token', 'urlResourceOwnerDetails' => 'https://api.provider.com/user' ]); ``` ``` -------------------------------- ### ResourceOwnerInterface::toArray Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-resource-owner.md Interface method to get all resource owner data as an associative array. ```php public function toArray(): array ``` -------------------------------- ### setGrantFactory / getGrantFactory Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-abstract-provider.md Set or get the grant factory instance used to resolve grant types. ```APIDOC ## setGrantFactory / getGrantFactory ### Description Set or get the grant factory instance used to resolve grant types. ### Methods - `setGrantFactory(GrantFactory $factory): self` - `getGrantFactory(): GrantFactory` ``` -------------------------------- ### AbstractProvider Core Methods Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/INDEX.md Reference for the AbstractProvider class, detailing its constructor, authorization URL generation, token exchange, protected resource requests, PKCE support, and state management. Key methods include getAuthorizationUrl, authorize, getAccessToken, getResourceOwner, getResponse, and getParsedResponse. ```APIDOC ## AbstractProvider ### Description Provides a base implementation for OAuth 2.0 providers, handling common tasks like authorization URL generation and token exchange. ### Key Methods - **getAuthorizationUrl()**: Generates the authorization URL for the OAuth 2.0 flow. - **authorize(array $params = [])**: Initiates the authorization process. - **getAccessToken(string $code, array $params = [])**: Exchanges an authorization code for an access token. - **getResourceOwner(AccessToken $token, array $params = [])**: Fetches the resource owner details. - **getResponse(RequestInterface $request)**: Gets the response from a request. - **getParsedResponse(ResponseInterface $response)**: Parses the response from the server. ``` -------------------------------- ### Enable S256 PKCE Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/configuration.md Enable S256 PKCE for enhanced security and broad compatibility. This is the recommended method. ```php $provider = new GenericProvider([ // ... options ... 'pkceMethod' => 'S256' ]); ``` -------------------------------- ### Get Authorization URL Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-abstract-provider.md Generates the authorization URL for user redirection, optionally specifying scopes. ```php $authUrl = $provider->getAuthorizationUrl([ 'scope' => ['user:email', 'user:profile'] ]); header('Location: ' . $authUrl); ``` -------------------------------- ### Get Refresh Token Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-access-token.md Retrieves the refresh token if it is present. This is useful for refreshing an expired access token. ```php public function getRefreshToken(): string|null ``` ```php $refreshToken = $token->getRefreshToken(); if ($refreshToken) { // Refresh the token $newToken = $provider->getAccessToken('refresh_token', [ 'refresh_token' => $refreshToken ]); } ``` -------------------------------- ### Get Default Scopes Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-abstract-provider.md Abstract method that must be implemented by subclasses to return the default scopes as an array. ```php abstract protected function getDefaultScopes(): array ``` -------------------------------- ### Client Credentials Grant with GenericProvider Source: https://github.com/thephpleague/oauth2-client/blob/master/docs/usage.md Demonstrates obtaining an access token using the client credentials grant type with a GenericProvider. Ensure all required provider URLs are configured. ```php // Note: the GenericProvider requires the `urlAuthorize` option, even though // it's not used in the OAuth 2.0 client credentials grant type. $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' ]); try { // Try to get an access token using the client credentials grant. $accessToken = $provider->getAccessToken('client_credentials'); } catch (\League\OAuth2\Client\\Provider\Exception\IdentityProviderException $e) { // Failed to get the access token exit($e->getMessage()); } ``` -------------------------------- ### Prepare Access Token Request Parameters Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-grants.md Prepares and validates parameters for an access token request. It merges default parameters with grant-specific options. ```php public function prepareRequestParameters(array $defaults, array $options): array ``` -------------------------------- ### Get Expiration Timestamp Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-access-token.md Retrieves the expiration timestamp of the token as a Unix timestamp. Returns null if the expiration is not set. ```php public function getExpires(): int|null ``` ```php $expires = $token->getExpires(); if ($expires) { echo "Expires at: " . date('Y-m-d H:i:s', $expires); } ``` -------------------------------- ### Get Base Authorization URL Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-abstract-provider.md Abstract method that must be implemented by subclasses to return the authorization endpoint URL. ```php abstract public function getBaseAuthorizationUrl(): string ``` -------------------------------- ### Typical OAuth 2.0 Flow with Resource Owner Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-resource-owner.md This snippet illustrates the complete OAuth 2.0 flow, from provider instantiation to fetching and accessing resource owner details. Ensure you have the necessary client ID, secret, and provider URLs configured. ```php // 1. Create provider $provider = new \League\OAuth2\Client\Provider\GenericProvider([ 'clientId' => 'your-client-id', 'clientSecret' => 'your-client-secret', 'redirectUri' => 'https://example.com/oauth/callback', 'urlAuthorize' => 'https://provider.com/oauth/authorize', 'urlAccessToken' => 'https://provider.com/oauth/token', 'urlResourceOwnerDetails' => 'https://api.provider.com/user', 'responseResourceOwnerId' => 'id' // Key containing user ID ]); // 2. Get authorization code (user redirected to provider login) $authUrl = $provider->getAuthorizationUrl(); // ... user logs in, gets redirected with code ... // 3. Exchange code for access token $token = $provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]); // 4. Fetch resource owner details $resourceOwner = $provider->getResourceOwner($token); // 5. Access resource owner data $userId = $resourceOwner->getId(); $userData = $resourceOwner->toArray(); echo "User ID: $userId"; echo "Name: " . $userData['name']; echo "Email: " . $userData['email']; ``` -------------------------------- ### Get All Token Values Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-access-token.md Returns all vendor-specific token values that are not part of the standard OAuth2 response. Useful for custom fields. ```php public function getValues(): array ``` ```php $token = new AccessToken([ 'access_token' => 'token123', 'expires_in' => 3600, 'scope' => 'read write', 'custom_field' => 'custom_value' ]); $values = $token->getValues(); echo $values['custom_field']; // 'custom_value' ``` -------------------------------- ### Get Resource Owner ID Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-access-token.md Retrieves the resource owner (user) ID associated with the token. Returns null if not present. ```php public function getResourceOwnerId(): string|null ``` ```php $userId = $token->getResourceOwnerId(); if ($userId) { echo "Token for user: $userId"; } ``` -------------------------------- ### Configuration Options Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/COMPLETION_SUMMARY.txt Details on available configuration options for providers. ```APIDOC ## Configuration Options ### Description Providers can be configured with various options to customize their behavior. ### Common Options - **clientId** (string): The client identifier. - **clientSecret** (string): The client secret. - **redirectUri** (string): The redirect URI registered with the authorization server. - **scopes** (array): An array of requested scopes. - **scopeSeparator** (string): The separator used for scopes (default: ','). ### Provider-Specific Options Refer to individual provider documentation for specific configuration options, such as `urlAuthorize`, `urlAccessToken`, and `urlResourceOwnerDetails`. ``` -------------------------------- ### Verify Client Configuration Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/errors.md Ensure that the client ID, client secret, and redirect URI are correctly configured to prevent client authentication failures. This snippet uses assertions to check these critical configuration values. ```php // Verify configuration assert($provider->clientId === 'correct-id'); assert($provider->clientSecret === 'correct-secret'); assert($provider->redirectUri === 'registered-redirect-uri'); ``` -------------------------------- ### Get Default Scopes Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-generic-provider.md Retrieves the default scopes configured for the provider. This is useful for understanding the permissions the application is requesting by default. ```php public function getDefaultScopes(): array|null ``` ```php $provider = new GenericProvider([ 'clientId' => '...', 'clientSecret' => '...', 'redirectUri' => '...', 'urlAuthorize' => '...', 'urlAccessToken' => '...', 'urlResourceOwnerDetails' => '...', 'scopes' => ['read', 'write'] ]); $scopes = $provider->getDefaultScopes(); ``` -------------------------------- ### Configure PKCE Method Source: https://github.com/thephpleague/oauth2-client/blob/master/docs/usage.md Configure the PKCE method for the Authorization Code grant. Use PKCE_METHOD_S256 for the strongest security. ```php $provider = new \League\OAuth2\Client\Provider\GenericProvider([ // ... // other options // ... 'pkceMethod' => \League\OAuth2\Client\Provider\GenericProvider::PKCE_METHOD_S256 ]); ``` -------------------------------- ### Get Base Authorization URL Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-generic-provider.md Retrieves the configured authorization URL for the provider. This is used to redirect users to authorize the application. ```php public function getBaseAuthorizationUrl(): string ``` ```php $authUrl = $provider->getBaseAuthorizationUrl(); ``` -------------------------------- ### Run Project Tests Source: https://github.com/thephpleague/oauth2-client/blob/master/CONTRIBUTING.md Execute the project's tests to ensure code quality and adherence to standards before submitting a pull request. This includes linting, unit testing, and code style checks. ```bash $ ./vendor/bin/parallel-lint src test $ ./vendor/bin/phpunit --coverage-text $ ./vendor/bin/phpcs src --standard=psr2 -sp ``` -------------------------------- ### Set/Get Option Provider Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-abstract-provider.md Set or get the option provider for customizing request options. This allows fine-grained control over request parameters. ```php public function setOptionProvider(OptionProviderInterface $provider): self public function getOptionProvider(): OptionProviderInterface ``` -------------------------------- ### Create PSR-7 Request with Simplified Options Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-tools.md Use getRequestWithOptions for a more concise way to create a PSR-7 Request, passing headers, body, and version within a single options array. ```php public function getRequestWithOptions( string $method, string $uri, array $options = [] ): Request ``` ```php $request = $factory->getRequestWithOptions('POST', 'https://api.example.com/data', [ 'headers' => ['Content-Type' => 'application/json'], 'body' => json_encode(['key' => 'value']) ]); ``` -------------------------------- ### Configure GenericProvider with Custom Collaborators Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/configuration.md Override default dependencies like the HTTP client or grant factory by providing custom instances in the second constructor parameter. ```php use GuzzleHttp\Client as HttpClient; use League\OAuth2\Client\Grant\GrantFactory; use League\OAuth2\Client\Tool\RequestFactory; use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider; $provider = new GenericProvider( [/* options */], [ 'httpClient' => new HttpClient(['timeout' => 30]), 'grantFactory' => new GrantFactory(), 'requestFactory' => new RequestFactory(), 'optionProvider' => new HttpBasicAuthOptionProvider(), ] ); ``` -------------------------------- ### Instantiate GenericProvider with HttpBasicAuthOptionProvider Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-option-providers.md Inject HttpBasicAuthOptionProvider when creating a GenericProvider to enable HTTP Basic Authentication for client credentials. ```php $provider = new \League\OAuth2\Client\Provider\GenericProvider( [ 'clientId' => '...', 'clientSecret' => '...', // ... other options ], [ 'optionProvider' => new \League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider() ] ); ``` -------------------------------- ### Get Base Access Token URL Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-abstract-provider.md Abstract method that must be implemented by subclasses to return the access token endpoint URL. ```php abstract public function getBaseAccessTokenUrl(array $params): string ``` -------------------------------- ### Get Grant Name as String Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-grants.md Returns the grant name, useful for request parameters. This method is part of the base AbstractGrant class. ```php public function __toString(): string ``` ```php $grant = new AuthorizationCode(); echo $grant; // 'authorization_code' ``` -------------------------------- ### Constants Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-abstract-provider.md Available constants for various configurations. ```APIDOC ## Constants ### Description Available constants for various configurations. ### Constants - `ACCESS_TOKEN_RESOURCE_OWNER_ID` - `METHOD_GET` - `METHOD_POST` - `PKCE_METHOD_S256` - `PKCE_METHOD_PLAIN` ``` -------------------------------- ### Get New Access Token with Refresh Token Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-grants.md Use this when the original access token has expired. Requires the refresh token from a previous authorization. ```php // Get new token using refresh token $newToken = $provider->getAccessToken('refresh_token', [ 'refresh_token' => $oldToken->getRefreshToken() ]); // Token properties echo $newToken->getToken(); echo $newToken->getRefreshToken(); ``` -------------------------------- ### Enable Plain Text PKCE Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/configuration.md Use plain text PKCE only if S256 is not available. This method is less secure as it does not encrypt the PKCE code. ```php $provider = new GenericProvider([ // ... options ... 'pkceMethod' => 'plain' ]); ``` -------------------------------- ### Instantiate AccessToken Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-access-token.md Create a new AccessToken instance using an array of options. The 'access_token' key is required. Optional keys include 'refresh_token', 'expires_in', 'expires', 'resource_owner_id', and vendor-specific fields. The constructor throws InvalidArgumentException if 'access_token' is missing or 'expires_in' is not numeric. ```php public function __construct(array $options = []) ``` ```php // From OAuth provider response $tokenData = json_decode($providerResponse, true); $token = new \League\OAuth2\Client\Token\AccessToken([ 'access_token' => 'abc123def456', 'token_type' => 'Bearer', 'expires_in' => 3600, 'refresh_token' => 'refresh123', 'resource_owner_id' => 'user123', 'scope' => 'read write' ]); // Vendor-specific fields are captured echo $token->getValues()['scope']; ``` -------------------------------- ### Implement Option Provider Interface Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/types.md Interface for customizing access token request formatting. It provides HTTP request options for token requests. ```php interface OptionProviderInterface { public function getAccessTokenOptions(string $method, array $params): array; } ``` -------------------------------- ### Get Redirect Limit Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-tools.md Retrieves the current maximum number of redirects that will be followed. This value determines how many redirect responses the client will process before stopping. ```php public function getRedirectLimit(): int ``` ```php $limit = $provider->getRedirectLimit(); echo "Max redirects: $limit"; ``` -------------------------------- ### Get List of Guarded Properties Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-tools.md Use getGuarded to retrieve an array containing the names of all properties that are protected from mass assignment. This is useful for introspection or debugging. ```PHP public function getGuarded(): array { return $this->guarded; } ``` -------------------------------- ### AbstractGrant - prepareRequestParameters Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-grants.md Prepares and validates access token request parameters, merging defaults with grant-specific options. ```APIDOC ## prepareRequestParameters ### Description Prepares and validates access token request parameters. ### Signature ```php public function prepareRequestParameters(array $defaults, array $options): array ``` ### Parameters #### Path Parameters This method does not have path parameters. #### Query Parameters This method does not have query parameters. #### Request Body This method does not have a request body. ### Parameters - **defaults** (array) - Required - Base parameters (typically `client_id`, `client_secret`, `redirect_uri`). - **options** (array) - Required - Grant-specific options. ### Returns Merged parameters ready for token request. ### Throws `BadMethodCallException` if required parameters are missing. ``` -------------------------------- ### Get Base Access Token URL Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-generic-provider.md Retrieves the configured URL for requesting an access token. This method is primarily for compatibility and does not use the provided parameters. ```php public function getBaseAccessTokenUrl(array $params): string ``` -------------------------------- ### getRequestWithOptions Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-tools.md Creates a PSR-7 Request using a simplified options array for headers, body, and version. ```APIDOC ## getRequestWithOptions ### Description Creates a PSR-7 Request using simplified options array. ### Method POST ### Endpoint /request/options ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **method** (string) - Required - HTTP method - **uri** (string) - Required - Request URI - **options** (array) - Optional - Options: `headers`, `body`, `version` ### Request Example ```php $request = $factory->getRequestWithOptions('POST', 'https://api.example.com/data', [ 'headers' => ['Content-Type' => 'application/json'], 'body' => json_encode(['key' => 'value']) ]); ``` ### Response #### Success Response (200) - **Request** (Request) - Guzzle `Request` instance. #### Response Example ```json { "example": "Guzzle Request Instance" } ``` ``` -------------------------------- ### AccessToken Initialization with Different Expiration Formats Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-access-token.md Demonstrates how the AccessToken class handles different formats for token expiration, including 'expires_in', 'expires' as a timestamp, and 'expires' as an offset. ```APIDOC ## Token Expiration Behavior ### Description The `AccessToken` class handles multiple expiration formats: ### Usage Examples ```php // Format 1: expires_in (seconds until expiration) $token = new AccessToken([ 'access_token' => 'xyz', 'expires_in' => 3600 // Expires in 1 hour ]); // Format 2: expires as timestamp $token = new AccessToken([ 'access_token' => 'xyz', 'expires' => time() + 3600 // Unix timestamp ]); // Format 3: expires as offset seconds (auto-detected) $token = new AccessToken([ 'access_token' => 'xyz', 'expires' => 1800 // Less than Oct 2012, so treated as seconds ]); ``` ``` -------------------------------- ### Set/Get Grant Factory Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-abstract-provider.md Set or get the grant factory instance used to resolve grant types. This is essential for managing different OAuth2 grant flows. ```php public function setGrantFactory(GrantFactory $factory): self public function getGrantFactory(): GrantFactory ``` -------------------------------- ### AccessTokenInterface Methods Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-access-token.md Lists the methods available through the AccessTokenInterface for retrieving token information and managing its state. ```APIDOC ## Interface Summary - AccessTokenInterface | Interface | Method | Purpose | |-----------|--------|---------| | AccessTokenInterface | getToken() | Get token string | | AccessTokenInterface | getRefreshToken() | Get refresh token | | AccessTokenInterface | getExpires() | Get expiration timestamp | | AccessTokenInterface | hasExpired() | Check expiration | | AccessTokenInterface | getValues() | Get vendor fields | | AccessTokenInterface | __toString() | String conversion | | AccessTokenInterface | jsonSerialize() | JSON serialization | ``` -------------------------------- ### Get Resource Owner Details URL Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-generic-provider.md Retrieves the configured URL for fetching resource owner details. The access token parameter is included for compatibility but is not used. ```php public function getResourceOwnerDetailsUrl(AccessToken $token): string ``` -------------------------------- ### Serialize and Deserialize AccessToken Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-access-token.md Demonstrates how to save an AccessToken object to a session by serializing it to JSON and how to restore it by deserializing the JSON data. ```php // Save to session $_SESSION['oauth_token'] = json_encode($token); // Restore from session $tokenData = json_decode($_SESSION['oauth_token'], true); $restoredToken = new AccessToken($tokenData); ``` -------------------------------- ### AccessToken Constructor Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-access-token.md Initializes a new AccessToken object with provided options. The constructor requires an 'access_token' and can optionally accept 'refresh_token', 'expires_in', 'expires', 'resource_owner_id', and vendor-specific fields. ```APIDOC ## Constructor ### Description Initializes a new AccessToken object with provided options. ### Signature ```php public function __construct(array $options = []) ``` ### Parameters #### Request Body - **options** (array) - Required - Token response data. Required: `access_token`. Optional: `refresh_token`, `expires_in`, `expires`, `resource_owner_id`, and any vendor-specific fields. ### Throws - `InvalidArgumentException` if `access_token` is not provided or `expires_in` is not numeric. ### Usage Example ```php // From OAuth provider response $tokenData = json_decode($providerResponse, true); $token = new \League\OAuth2\Client\Token\AccessToken([ 'access_token' => 'abc123def456', 'token_type' => 'Bearer', 'expires_in' => 3600, 'refresh_token' => 'refresh123', 'resource_owner_id' => 'user123', 'scope' => 'read write' ]); // Vendor-specific fields are captured echo $token->getValues()['scope']; ``` ``` -------------------------------- ### Implement Resource Owner Interface Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/types.md Interface for resource owner (authenticated user) implementations. Provides methods to get the owner's ID and all associated data. ```php interface ResourceOwnerInterface { public function getId(): mixed; public function toArray(): array; } ``` -------------------------------- ### AbstractProvider Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/COMPLETION_SUMMARY.txt Documentation for the abstract base provider class, outlining common methods and properties for OAuth 2.0 providers. ```APIDOC ## AbstractProvider ### Description Provides a base implementation for OAuth 2.0 providers, handling common logic for authorization and token retrieval. ### Methods #### `getAuthorizationUrl(array $options = [])` ##### Description Generates the authorization URL for the OAuth 2.0 flow. ##### Method GET ##### Endpoint N/A (Client-side method) ##### Parameters ###### Query Parameters - **options** (array) - Optional - Additional options for the authorization URL. ##### Return Type string - The generated authorization URL. ##### Example ```php $provider->getAuthorizationUrl(); ``` #### `getAccessToken(string $grant, array $options = [])` ##### Description Requests an access token from the authorization server. ##### Method POST ##### Endpoint N/A (Client-side method) ##### Parameters ###### Query Parameters - **grant** (string) - Required - The grant type being used (e.g., 'authorization_code'). - **options** (array) - Optional - Additional options for the token request. ##### Return Type League\OAuth2\Client\Token\AccessTokenInterface - The access token object. ##### Example ```php $provider->getAccessToken('authorization_code', ['code' => $code]); ``` #### `getResourceOwner(AccessTokenInterface $accessToken)` ##### Description Fetches the resource owner details using the provided access token. ##### Method GET ##### Endpoint N/A (Client-side method) ##### Parameters ###### Path Parameters - **accessToken** (AccessTokenInterface) - Required - The access token object. ##### Return Type League\OAuth2\Client\ResourceOwnerInterface - The resource owner object. ##### Example ```php $provider->getResourceOwner($accessToken); ``` ``` -------------------------------- ### Abstract Methods for Provider Implementation Source: https://github.com/thephpleague/oauth2-client/blob/master/docs/providers/implementing.md These are the core abstract methods that must be implemented when extending AbstractProvider. Each method has specific expectations for its behavior. ```php 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); ``` -------------------------------- ### Get Access Token (Client Credentials) Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/README.md Obtain an access token using the client credentials grant type. Suitable for server-to-server authentication where no user interaction is involved. ```php // Client credentials (server-to-server) $token = $provider->getAccessToken('client_credentials'); ``` -------------------------------- ### GenericResourceOwner Constructor Usage Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-resource-owner.md Instantiate `GenericResourceOwner` with the raw response data and the key name for the resource owner's ID. ```php $response = [ 'id' => 12345, 'name' => 'John Doe', 'email' => 'john@example.com' ]; $owner = new League\OAuth2\Client\Provider\GenericResourceOwner($response, 'id'); echo $owner->getId(); // 12345 ``` -------------------------------- ### GenericProvider Configuration Options Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-generic-provider.md The GenericProvider can be configured with various options to customize its behavior. This includes required options for server endpoints, optional settings for token and response handling, and Guzzle HTTP client options. ```APIDOC ## GenericProvider Configuration ### Required Options - **urlAuthorize** (string): Authorization server URL for user approval. - **urlAccessToken** (string): Token server URL for exchanging credentials. - **urlResourceOwnerDetails** (string): API endpoint for fetching user/resource owner information. ### Optional Options - **accessTokenMethod** (string): HTTP method for token requests. Defaults to 'POST'. Can be 'GET' or 'POST'. - **accessTokenResourceOwnerId** (string): Key in access token response identifying resource owner. Defaults to null. - **scopeSeparator** (string): Delimiter for joining scope array into string. Defaults to ','. - **responseError** (string): Key in response containing error message. Defaults to 'error'. - **responseCode** (string): Key in response containing error code. Defaults to null. - **responseResourceOwnerId** (string): Key in resource owner response containing the ID. Defaults to 'id'. - **scopes** (array): Default scopes to request. Defaults to null. - **pkceMethod** (string): PKCE method. Can be 'S256' or 'plain', or null to disable. Defaults to null. ### Guzzle HTTP Client Options - **timeout** (float): Request timeout in seconds. - **proxy** (string): HTTP proxy URL. ``` -------------------------------- ### Send HTTP Request and Get Response Source: https://github.com/thephpleague/oauth2-client/blob/master/_autodocs/api-reference-abstract-provider.md Executes a PSR-7 HTTP request and returns the corresponding PSR-7 response object. This method is fundamental for interacting with any API endpoint. ```php public function getResponse(RequestInterface $request): ResponseInterface ``` ```php $request = $provider->getRequest('GET', 'https://api.provider.com/data'); $response = $provider->getResponse($request); echo $response->getStatusCode(); // 200 ```