Information Security 6 min read

How to Build an OAuth2 Authorization Code Server in PHP

This article explains the OAuth2 authorization code flow and provides a step‑by‑step guide to creating a PHP‑based authorization server, including installing the bshaffer/oauth2‑server‑php library, writing the server code, setting up the MySQL client table, and testing token requests.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Build an OAuth2 Authorization Code Server in PHP

OAuth is an open standard for delegating access to user resources, separating the user from the resource server and providing a more secure authorization process. This guide shows how to create an OAuth2 authorization‑code server using PHP.

The authorization‑code grant works as follows:

The client sends an authorization request to the server.

The server authenticates the user and asks for consent.

After the user approves, the server issues an authorization code to the client.

The client exchanges the code, along with its client ID and secret, for an access token.

The server validates the request and returns the token.

The client uses the token to access protected resources on the resource server.

First, install a popular PHP OAuth2 library, such as composer require bshaffer/oauth2-server-php , using Composer.

Next, create an index.php file that acts as the authorization server. The essential code is shown below:

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

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

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

// Create the server
$server = new OAuth2Server($storage);
$server->addGrantType(new OAuth2GrantTypeAuthorizationCode($storage));

$request = OAuth2Request::createFromGlobals();
$response = new OAuth2Response();
if (!$server->validateAuthorizeRequest($request, $response)) {
    $response->send();
    die;
}

if (empty($_POST)) {
    exit('
\n
Username:
\n
Password:
\n
\n
');
}

$is_authorized = ($_POST['username'] == 'admin' && $_POST['password'] == 'admin');
$server->handleAuthorizeRequest($request, $response, $is_authorized);
if ($is_authorized) {
    $response->send();
} else {
    echo '授权失败';
}

Then create a MySQL table to store client information:

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`)
);

To test the server, open a browser and visit a URL such as:

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

Replace YOUR_CLIENT_ID , YOUR_REDIRECT_URI , and SCOPE with your actual values. The server will prompt for a username and password; use admin for both in this example. After successful login you will receive an authorization code.

Exchange the code for an access token with a POST request, for example using curl:

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 AUTHORIZATION_CODE , YOUR_CLIENT_ID , YOUR_CLIENT_SECRET , and YOUR_REDIRECT_URI with the appropriate values. If everything is correct, the response will contain an access token that can be used to call protected APIs.

This step‑by‑step guide demonstrates how to set up a secure OAuth2 authorization‑code server in PHP, helping you protect user data and implement reliable third‑party access.

backendsecurityPHPOAuth2authorization-server
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.