在PHP中實現單點登錄(Single Sign-On,簡稱SSO)通常涉及以下幾個步驟:
用戶認證:首先,用戶需要在一個認證中心進行登錄,認證中心會驗證用戶的身份并頒發一個認證憑證(通常是令牌)。
令牌傳遞:用戶在訪問其他需要登錄的應用時,會將認證憑證(令牌)攜帶在請求頭中傳遞給這些應用。
令牌驗證:應用接收到令牌后,會向認證中心發送請求以驗證令牌的有效性。
用戶會話:一旦令牌被驗證有效,認證中心會創建或更新用戶的會話信息,應用可以根據會話信息判斷用戶是否已經登錄。
下面是一個簡單的示例,使用PHP和JWT(JSON Web Token)來實現單點登錄:
首先,你需要安裝一個JWT庫,例如 firebase/php-jwt
。你可以通過Composer來安裝:
composer require firebase/php-jwt
創建一個認證中心,負責用戶的登錄和令牌的生成與驗證。
<?php
require_once 'vendor/autoload.php';
use Firebase\JWT\JWK;
use Firebase\JWT\JWT;
class AuthCenter {
private $secretKey = 'your_secret_key';
public function login($username, $password) {
// 這里應該連接數據庫并驗證用戶名和密碼
if ($username === 'admin' && $password === 'password') {
$token = [
'iss' => 'http://example.com',
'iat' => time(),
'exp' => time() + 3600,
'userId' => $username
];
return JWT::encode($token, $this->secretKey, 'HS256');
}
return null;
}
public function verifyToken($token) {
try {
$decoded = JWT::decode($token, new JWK([$this->secretKey]), ['HS256']);
return $decoded->userId;
} catch (Exception $e) {
return null;
}
}
}
?>
創建一個應用,負責接收令牌并驗證用戶身份。
<?php
require_once 'vendor/autoload.php';
use Firebase\JWT\JWK;
use Firebase\JWT\JWT;
class Application {
private $authCenter;
public function __construct(AuthCenter $authCenter) {
$this->authCenter = $authCenter;
}
public function handleRequest($token) {
$userId = $this->authCenter->verifyToken($token);
if ($userId) {
echo "Welcome, $userId! You are logged in.";
} else {
echo "Invalid token. Please log in again.";
}
}
}
?>
創建一個簡單的HTTP服務器來測試單點登錄。
<?php
require_once 'vendor/autoload.php';
use Firebase\JWT\JWK;
use Firebase\JWT\JWT;
class AuthCenter {
private $secretKey = 'your_secret_key';
public function login($username, $password) {
if ($username === 'admin' && $password === 'password') {
$token = [
'iss' => 'http://example.com',
'iat' => time(),
'exp' => time() + 3600,
'userId' => $username
];
return JWT::encode($token, $this->secretKey, 'HS256');
}
return null;
}
public function verifyToken($token) {
try {
$decoded = JWT::decode($token, new JWK([$this->secretKey]), ['HS256']);
return $decoded->userId;
} catch (Exception $e) {
return null;
}
}
}
class Application {
private $authCenter;
public function __construct(AuthCenter $authCenter) {
$this->authCenter = $authCenter;
}
public function handleRequest($token) {
$userId = $this->authCenter->verifyToken($token);
if ($userId) {
echo "Welcome, $userId! You are logged in.";
} else {
echo "Invalid token. Please log in again.";
}
}
}
$authCenter = new AuthCenter();
$application = new Application($authCenter);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$token = $_POST['token'];
$application->handleRequest($token);
} else {
echo '<form method="post">
<input type="hidden" name="token" value="' . $authCenter->login('admin', 'password') . '">
<input type="submit" value="Log In">
</form>';
}
?>
你可以使用Postman或其他HTTP客戶端工具來測試單點登錄功能。首先訪問認證頁面,輸入用戶名和密碼,獲取令牌。然后將令牌傳遞給應用頁面,應用會驗證令牌并顯示歡迎信息。
通過這種方式,你可以實現一個簡單的單點登錄系統。實際應用中,你可能需要添加更多的安全措施,例如HTTPS、數據庫驗證、密碼加密等。