OAuth 是一種開放標準,允許第三方應用安全地訪問用戶的資源。在OAuth2 中,授權碼授權是最常見的授權類型。本文將詳細介紹如何在PHP 中構建一個授權碼授權服務器,幫助你實現安全可靠的用戶授權。
授權碼授權流程如下:
首先,安裝一個流行的PHP OAuth2 庫。我們將使用"bshaffer/oauth2-server-php" 這個庫,它可以通過Composer 安裝:
composer require bshaffer/oauth2-server-php
接下來,我們在PHP 中創建一個`index.php` 文件,作為我們的授權碼授權服務器:
<?php require_once 'vendor/autoload.php'; // 創建 PDO 實例連接數據庫 $dsn = "mysql:dbname=testdb;host=localhost"; $username = "root"; $password = ""; $pdo = new PDO($dsn, $username, $password); // 創建 OAuth2 存儲庫實例 $storage = new OAuth2StoragePdo($pdo); // 創建授权服务器实例 $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(' <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 '授權失敗'; }
現在,我們需要創建一個用於存儲客戶端信息的數據庫表。在MySQL 中執行以下SQL 語句:
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`) );
訪問以下URL 進行授權:
http://localhost/index.php?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&scope=SCOPE
在授權頁面輸入用戶名和密碼(如:用戶名和密碼均為"admin"),授權碼將被返回。如果用戶驗證成功,服務器會返回一個授權碼。
通過curl 或其他HTTP 客戶端,使用獲取到的授權碼來請求訪問令牌:
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
將授權碼、客戶端ID、客戶端密鑰和重定向URI 替換為實際值。如果請求成功,你將獲得訪問令牌。
以上就是如何在PHP 中創建一個授權碼授權服務器的完整過程。通過使用OAuth2,你可以為你的應用程序實現安全的授權流程,保護用戶的數據隱私。