sempoinus1/php-oauth

Lightweight and extensible PHP OAuth2 library supporting multiple providers like Keycloak, Google, and Microsoft.

v1.0.0 2025-02-25 21:28 UTC

This package is not auto-updated.

Last update: 2025-06-18 20:18:00 UTC


README

Introduction

This is a framework-agnostic PHP library for implementing OAuth2 authentication. The library supports multiple grant types, including Client Credentials, and can store tokens in a database (PDOStorage) or session (SessionStorage).

Features

  • OAuth2 authentication
  • Client Credentials grant type
  • Token storage using:
    • Database (PDO)
    • PHP sessions
  • Extendable provider support (Google, Microsoft, Keycloak)

Installation

composer require yournamespace/oauth2-library

Directory Structure

src/
│── OAuth2/
│   ├── GrantType/          # Different OAuth2 grant types
│   ├── Storage/            # Token and client storage
│   ├── Token/              # Token management
│   ├── Provider/           # OAuth2 Providers (Google, Microsoft, Keycloak)
│   ├── Server.php          # Main OAuth2 server handler

Usage

1. Setting up the OAuth2 Server

Using PDOStorage (Database)

require 'vendor/autoload.php';

use Sempoinus1\PhpOauth\OAuth2\Server;
use Sempoinus1\PhpOauth\OAuth2\GrantType\ClientCredentials;
use Sempoinus1\PhpOauth\OAuth2\Storage\PDOStorage;

$pdo = new PDO('mysql:host=localhost;dbname=oauth2', 'user', 'password');
$storage = new PDOStorage($pdo);

$server = new Server($storage);
$server->addGrantType('client_credentials', new ClientCredentials($storage));

Using SessionStorage

use Sempoinus1\PhpOauth\OAuth2\Storage\SessionStorage;

$storage = new SessionStorage();
$server = new Server($storage);
$server->addGrantType('client_credentials', new ClientCredentials($storage));

2. Handling Token Requests

$request = [
    'grant_type' => 'client_credentials',
    'client_id' => 'test_client',
    'client_secret' => 'test_secret'
];

$response = $server->handleTokenRequest($request);
echo json_encode($response);

3. Validating Tokens

$token = 'received_token_here';
if ($storage->validateToken($token)) {
    echo 'Token is valid!';
} else {
    echo 'Invalid token!';
}

Storage Implementations

PDOStorage.php

Used for database-backed storage.

$pdo = new PDO('mysql:host=localhost;dbname=oauth2', 'user', 'password');
$storage = new PDOStorage($pdo);

SessionStorage.php

Used for temporary in-memory storage.

$storage = new SessionStorage();

Extending with OAuth2 Providers (Google, Microsoft, Keycloak)

use Sempoinus1\PhpOauth\OAuth2\Provider\Google;

$google = new Google('client_id', 'client_secret', 'https://yourapp.com/callback');
$authUrl = $google->getAuthUrl();

echo "<a href='$authUrl'>Login with Google</a>";

Roadmap

  • Implement more grant types (Authorization Code, Refresh Token)
  • Extend provider support (Facebook, GitHub, etc.)

License

MIT License