Overview of OAuth 2.0 Client
masterleague/oauth2-client package provides a standardized base for integrating with OAuth 2.0 service providers. It handles the complexities of RFC 6749, allowing you to implementrepository·master·Indexed 26 days ago
https://github.com/thephpleague/oauth2-clientA 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.
league/oauth2-client package provides a standardized base for integrating with OAuth 2.0 service providers. It handles the complexities of RFC 6749, allowing you to implementTo 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);To integrate with OAuth 2.0 providers not natively supported by league/oauth2-client, you can use community-maintained third-party provider clients. These packages all depend on league/oauth2-client.
Install a specific provider using Composer by running:
$ composer require [vendor/package-name]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().
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());
}The Authorization Code grant is the most common method for authenticating users with a third-party service. Using the GenericProvider, you must:
getAuthorizationUrl().state in a session to prevent CSRF attacks.state matches the stored one.code for an access token using getAccessToken('authorization_code', ['code' => $_GET['code']]).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());
}
}GenericProvider class out-of-the-box. For more detailed implementation steps and code examples, refer to the basic usage guide.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-clientThe 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:
league/oauth2-facebookleague/oauth2-githubleague/oauth2-googleleague/oauth2-instagramleague/oauth2-linkedin$ composer require league/<package-name>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());
}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());
}Ensure your environment meets the supported PHP version requirements before installing the package. The library supports the following versions: