sempoinus1/php-oauth
最新稳定版本:v1.0.0
Composer 安装命令:
composer require sempoinus1/php-oauth
包简介
Lightweight and extensible PHP OAuth2 library supporting multiple providers like Keycloak, Google, and Microsoft.
README 文档
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 sempoinus1/php-oauth2
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
统计信息
- 总下载量: 1
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 1
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-02-25