Current Location: Home> Latest Articles> PHP OAuth2 Authorization: A Complete Guide to Building an Authorization Code Authorization Server

PHP OAuth2 Authorization: A Complete Guide to Building an Authorization Code Authorization Server

M66 2025-06-21

PHP OAuth2 Authorization: A Complete Guide to Building an Authorization Code Authorization Server

OAuth is an open standard that allows third-party applications to securely access user resources. In OAuth2, the authorization code grant is the most commonly used authorization type. In this article, we will show you how to build an authorization code authorization server in PHP, providing you with a secure and reliable authentication process.

Overview of OAuth2 Authorization Code Flow

The authorization code grant flow is as follows:

  1. The client sends an authorization request to the authorization server.
  2. The authorization server verifies the user's identity and requests authorization.
  3. Once the user grants authorization, the authorization server issues an authorization code to the client.
  4. The client sends the authorization code along with the client ID, client secret, and other necessary information to the authorization server to request an access token.
  5. The authorization server validates the information and issues an access token.
  6. The client uses the access token to access the resource server to retrieve user data.

Install PHP OAuth2 Library

First, install a popular PHP OAuth2 library. We will use the "bshaffer/oauth2-server-php" library, which can be installed via Composer:

composer require bshaffer/oauth2-server-php

Create the Authorization Server

Next, we create an `index.php` file as our authorization code authorization server:

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

// Create PDO instance to connect to the database
$dsn = "mysql:dbname=testdb;host=localhost";
$username = "root";
$password = "";
$pdo = new PDO($dsn, $username, $password);

// Create OAuth2 storage instance
$storage = new OAuth2StoragePdo($pdo);

// Create the authorization server instance
$server = new OAuth2Server($storage);

// Add supported grant types
$server->addGrantType(new OAuth2GrantTypeAuthorizationCode($storage));

// Handle authorization request
$request = OAuth2Request::createFromGlobals();
$response = new OAuth2Response();

if (!$server->validateAuthorizeRequest($request, $response)) {
    $response->send();
    die();
}

// Show authorization page
if (empty($_POST)) {
    exit('
        <form method="post">
            <label for="username">Username:</label>
            <input type="text" id="username" name="username"><br><br>
            <label for="password">Password:</label>
            <input type="password" id="password" name="password"><br><br>
            <input type="submit" value="Authorize">
        </form>
    ');
}

$is_authorized = ($_POST['username'] == 'admin' && $_POST['password'] == 'admin');

$server->handleAuthorizeRequest($request, $response, $is_authorized);

if ($is_authorized) {
    $response->send();
} else {
    echo 'Authorization failed';
}

Create the Database Table

Now, we need to create a database table to store client information. Execute the following SQL query in MySQL:

CREATE TABLE `oauth_clients` (
    `client_id` varchar(80) COLLATE utf8_unicode_ci NOT NULL,
    `client_secret` varchar(80) COLLATE utf8_unicode_ci NOT NULL,
    `redirect_uri` varchar(2000) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
    `grant_types` varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL,
    `scope` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
    `user_id` varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL,
    PRIMARY KEY (`client_id`)
);
  

Test the Authorization Code Flow

To test the authorization process, visit the following URL:

http://localhost/index.php?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&scope=SCOPE
  

On the authorization page, enter the username and password (e.g., both "admin"). After successful authentication, you will receive an authorization code.

Request the Access Token

Use curl or any other HTTP client to request an access token using the received authorization code:

curl -X POST -d "grant_type=authorization_code&code=AUTHORIZATION_CODE&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&redirect_uri=YOUR_REDIRECT_URI" http://localhost/token.php
  

Replace the authorization code, client ID, client secret, and redirect URI with your actual values. If everything works correctly, you will receive an access token in response.

Conclusion

In this article, we have shown you how to set up an authorization code authorization server in PHP. Using OAuth2 provides a secure and reliable way to implement user authorization while protecting their data privacy.