Implementing OAuth 2.0 Authentication in PHP

OAuth 2.0 is a popular authorization framework that allows applications to access a user’s account information without exposing their credentials. It’s widely used by major platforms like Google, Facebook, and GitHub.

What is OAuth 2.0?

OAuth 2.0 is an authorization framework designed to allow third-party applications to obtain limited access to a web service. Instead of requiring the user to provide their login credentials, the user authenticates with the service and grants the application access to specific information (like an email address or profile).

In OAuth 2.0, there are four roles:

  • Resource Owner: The user who authorizes an application to access their data.
  • Client: The application requesting access to the user’s data.
  • Resource Server: The server hosting the user’s data.
  • Authorization Server: The server issuing access tokens to the client.

OAuth 2.0 Authorization Flow

The OAuth 2.0 flow generally involves the following steps:

  1. Authorization Request: The client directs the user to the authorization server to approve access.
  2. Authorization Grant: If the user approves, the authorization server provides an authorization code.
  3. Token Request: The client exchanges the authorization code for an access token.
  4. Access Token: The client uses the access token to access the resource server and retrieve user information.

Setting Up a PHP Project

Let’s get started by setting up a PHP project. You can use any web server like Apache or Nginx, but for simplicity, I’ll assume you’re using a local environment like XAMPP or MAMP.

  1. Create a Project Directory:

    mkdir oauth2-php
    cd oauth2-php
  2. Set Up Composer: If you don’t have Composer installed, you can download it from getcomposer.org. Then, in your project directory, run:

    composer init
  3. Create the Entry Point: Create an index.php file, which will be our entry point for handling OAuth 2.0 authentication.

Installing a PHP OAuth Library

Instead of writing the OAuth 2.0 flow from scratch, I’ll use the popular PHP package league/oauth2-client. It simplifies the process and handles token management.

Install the library via Composer:

composer require league/oauth2-client

Building the OAuth 2.0 Flow in PHP

Let’s assume we’re using Google as the OAuth provider. To start, you need to create credentials for your app in the Google Developer Console:

  1. Go to the Google Developer Console.
  2. Create a new project and enable the Google+ API or Google People API.
  3. Set up OAuth credentials (client ID, client secret, and redirect URI).

Here’s the PHP code to initiate the OAuth flow:

<?php
require_once 'vendor/autoload.php';

use League\OAuth2\Client\Provider\Google;

session_start();

// Set up the OAuth 2.0 provider
$provider = new Google([
    'clientId'     => 'YOUR_GOOGLE_CLIENT_ID',
    'clientSecret' => 'YOUR_GOOGLE_CLIENT_SECRET',
    'redirectUri'  => 'http://localhost/oauth2-php/callback.php',
]);

// Step 1: Redirect user to Google authorization page
if (!isset($_GET['code'])) {
    $authorizationUrl = $provider->getAuthorizationUrl();
    $_SESSION['oauth2state'] = $provider->getState();
    header('Location: ' . $authorizationUrl);
    exit;
}

You need to handle the callback from Google and exchange the authorization code for an access token. Create a callback.php file:

<?php
require_once 'vendor/autoload.php';

use League\OAuth2\Client\Provider\Google;

session_start();

// Set up the OAuth 2.0 provider
$provider = new Google([
    'clientId'     => 'YOUR_GOOGLE_CLIENT_ID',
    'clientSecret' => 'YOUR_GOOGLE_CLIENT_SECRET',
    'redirectUri'  => 'http://localhost/oauth2-php/callback.php',
]);

// Step 2: Exchange authorization code for an access token
if (isset($_GET['code'])) {
    $accessToken = $provider->getAccessToken('authorization_code', [
        'code' => $_GET['code']
    ]);

    // Use the access token to get user information
    $resourceOwner = $provider->getResourceOwner($accessToken);

    // Print user information
    echo 'Hello, ' . $resourceOwner->getFirstName() . ' ' . $resourceOwner->getLastName();
}

Handling Tokens and User Data

Once you have the access token, you can use it to make authorized API requests on behalf of the user. For example, you can use it to fetch user profile information or perform actions within the user’s account.

Be sure to handle tokens securely and refresh them as needed. OAuth 2.0 often includes refresh tokens that can be used to obtain new access tokens without requiring the user to re-authenticate.

For more details, refer to the OAuth 2.0 specification and the league/oauth2-client documentation.