php的token管理类(AI生成)

当然,以下是一个简单的 PHP 类,用于生成和管理令牌(token)。这个类可以生成一个随机的令牌、验证令牌是否有效,并允许设置一个令牌的过期时间。

<?php

class Token
{
    private $secretKey;
    private $token;
    private $expiration;

    /**
     * Token constructor.
     * @param string $secretKey 用于生成和验证令牌的密钥
     */
    public function __construct($secretKey)
    {
        $this->secretKey = $secretKey;
    }

    /**
     * 生成一个新的令牌
     * @param int $expirationTime 令牌的有效期(秒)
     * @return string 生成的令牌
     */
    public function generateToken($expirationTime = 3600)
    {
        $data = [
            'iat' => time(), // 令牌生成时间
            'exp' => time() + $expirationTime // 令牌过期时间
        ];

        $jwt = $this->encode($data);
        $this->token = $jwt;
        $this->expiration = time() + $expirationTime;

        return $jwt;
    }

    /**
     * 验证令牌是否有效
     * @param string $token 要验证的令牌
     * @return bool 是否有效
     */
    public function validateToken($token)
    {
        $decoded = $this->decode($token);

        if (!$decoded || $decoded->exp < time()) {
            return false;
        }

        return true;
    }

    /**
     * 编码数据为 JWT
     * @param array $data 要编码的数据
     * @return string 编码后的 JWT
     */
    private function encode($data)
    {
        $header = base64_encode(json_encode(['typ' => 'JWT', 'alg' => 'HS256']));
        $payload = base64_encode(json_encode($data));
        $signature = hash_hmac('sha256', "$header.$payload", $this->secretKey, true);
        $signature = base64_encode($signature);

        return "$header.$payload.$signature";
    }

    /**
     * 解码 JWT
     * @param string $jwt 要解码的 JWT
     * @return stdClass|null 解码后的数据或 null
     */
    private function decode($jwt)
    {
        $parts = explode('.', $jwt);

        if (count($parts) !== 3) {
            return null;
        }

        list($header, $payload, $signature) = $parts;

        $decodedSignature = base64_decode($signature);
        $data = "$header.$payload";
        $calculatedSignature = hash_hmac('sha256', $data, $this->secretKey, true);

        if (hash_equals($decodedSignature, $calculatedSignature)) {
            return json_decode($base64_decode($payload));
        }

        return null;
    }

    /**
     * 获取当前令牌的过期时间
     * @return int|null 过期时间戳或 null(如果没有令牌)
     */
    public function getExpiration()
    {
        return $this->expiration;
    }

    /**
     * 获取当前令牌
     * @return string|null 当前令牌或 null(如果没有令牌)
     */
    public function getToken()
    {
        return $this->token;
    }
}

// 使用示例
$secretKey = 'your-secret-key';
$token = new Token($secretKey);

// 生成一个有效期为1小时的令牌
$newToken = $token->generateToken(3600);
echo "Generated Token: " . $newToken . PHP_EOL;

// 验证令牌是否有效
$isValid = $token->validateToken($newToken);
echo "Is Token Valid: " . ($isValid ? 'Yes' : 'No') . PHP_EOL;

// 获取令牌过期时间
$expiration = $token->getExpiration();
echo "Token Expiration: " . date('Y-m-d H:i:s', $expiration) . PHP_EOL;

解释

  1. 构造函数:接受一个 secretKey 用于生成和验证令牌。
  2. 生成令牌:generateToken 方法生成一个新的 JWT 令牌,并设置其过期时间。
  3. 验证令牌:validateToken 方法验证给定的令牌是否有效。
  4. 编码和解码:encode 和 decode 方法用于 JWT 的编码和解码。
  5. 获取过期时间和令牌:提供 getExpiration 和 getToken 方法来获取当前令牌的过期时间和令牌本身。

这个类使用 JWT(JSON Web Token)标准来生成和验证令牌。你可以根据具体需求进行扩展和修改。

posted @ 2025-01-15 16:28  充实地生活着  阅读(44)  评论(0)    收藏  举报