OAuth client for PHP: complete guide to authentication integration
OAuth (Open Authorization) is an open authorization protocol that allows a third party to be granted limited access to user resources without sharing a login and password. In the PHP world, there are several libraries for implementing OAuth 2.0, but one of the most popular and well-maintained is League\\OAuth2-Client (The PHP League). This library provides a flexible and secure way to integrate login via Google, Facebook, GitHub, VK (VKontakte), Yandex, and many other services.
In this article, we will thoroughly cover the installation, configuration, and usage of an OAuth client for PHP using authentication via Google and VK as examples. You will learn how to obtain an access token, refresh token, and user profile data.
Installing the OAuth client via Composer
To get started, you need to install the main library and providers (adapters for specific services). Run the following in your terminal:
composer require league/oauth2-clientcomposer require league/oauth2-googlecomposer require league/oauth2-vkThe library supports PSR-7 (HTTP messages) and PSR-18 (HTTP client), so it is also recommended to install Guzzle or any other compatible HTTP client:
composer require guzzlehttp/guzzleBasic OAuth 2.0 architecture
OAuth 2.0 in PHP works according to the following scheme:
- Client ID and Client Secret — obtained when registering your application with the service (Google Cloud Console, VK Developers, etc.).
- Redirect URI — the URL on your website where the service will redirect the user after authorization.
- Authorization Code — a temporary code that is exchanged for an access token.
- Access Token — the key for accessing the user's API.
- Refresh Token — allows you to refresh the access token without re-authorization.
Example: login via Google
Let's create a simple handler for authentication via Google. It is assumed that you already have a client_id and client_secret.
Step 1. Redirect the user to the Google authorization page
<?phprequire 'vendor/autoload.php';
$provider = new \\League\\OAuth2\\Client\\Provider\\Google([ 'clientId' => 'YOUR_CLIENT_ID', 'clientSecret' => 'YOUR_CLIENT_SECRET', 'redirectUri' => 'https://your-site.com/callback.php',]);
// Generate the authorization URL$authUrl = $provider->getAuthorizationUrl([ 'scope' => ['email', 'profile'], // requested permissions]);
// Save the state in the session for CSRF protection$_SESSION['oauth2state'] = $provider->getState();
header('Location: ' . $authUrl);exit;Step 2. Handle the callback (callback.php)
<?phpsession_start();require 'vendor/autoload.php';
$provider = new \\League\\OAuth2\\Client\\Provider\\Google([ 'clientId' => 'YOUR_CLIENT_ID', 'clientSecret' => 'YOUR_CLIENT_SECRET', 'redirectUri' => 'https://your-site.com/callback.php',]);
// Check the state to prevent CSRF attacksif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { unset($_SESSION['oauth2state']); exit('Invalid state');}
try { // Exchange the authorization code for an access token $accessToken = $provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]);
// Get the user's profile data $resourceOwner = $provider->getResourceOwner($accessToken); $user = $resourceOwner->toArray();
echo "Hello, " . htmlspecialchars($user['name']) . "!"; echo "Email: " . htmlspecialchars($user['email']); // Save the token to the database for Also in library
Swagger/OpenAPI Generation for Java: Libraries and Tools
Testing in TypeScript: A Complete Guide to Frameworks and Tools
Geolocation and Maps in C# (.NET): Overview of Libraries and Tools