How to Build an OAuth2 Authorization Code Server in PHP
This article explains how to set up an OAuth2 authorization code server using PHP, detailing the OAuth flow, required Composer library, PHP implementation code, MySQL client table creation, and testing steps with example curl requests to obtain access tokens.
OAuth is an open standard for delegating access to user resources, built on HTTP, separating users from resource servers for secure authorization.
The Authorization Code grant, the most common OAuth2 flow, proceeds as follows:
The client initiates an authorization request to the authorization server.
The server authenticates the user and asks for consent.
Upon approval, 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 client and code, then issues the access token.
The client uses the access token to request the user's resources from the resource server.
To implement this in PHP, install a library such as bshaffer/oauth2-server-php via Composer:
composer require bshaffer/oauth2-server-phpCreate index.php with the following code to set up the PDO storage, OAuth2 server, and handle authorization requests:
<?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 an authorization server instance
$server = new OAuth2Server($storage);
// Add supported grant type
$server->addGrantType(new OAuth2GrantTypeAuthorizationCode($storage));
// Process the authorization request
$request = OAuth2Request::createFromGlobals();
$response = new OAuth2Response();
if (!$server->validateAuthorizeRequest($request, $response)) {
$response->send();
die;
}
// Show authorization form
if (empty($_POST)) {
exit('
Username:
Password:
');
}
// Handle authorization decision
$is_authorized = ($_POST["username"] == "admin" && $_POST["password"] == "admin");
$server->handleAuthorizeRequest($request, $response, $is_authorized);
if ($is_authorized) {
$response->send();
} else {
echo '授权失败';
}
?>Define a MySQL table to store client credentials:
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 server by visiting http://localhost/index.php?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&scope=SCOPE , logging in with username and password “admin”, and then exchanging the received code for an access token using a curl request:
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.phpIf successful, the server returns an access token that can be used to access protected resources.
This guide demonstrates the complete steps to create a secure OAuth2 authorization code server in PHP.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.