php Jwt接口安全示例
时间: 2023-02-08 22:13:28 浏览: 122
PHP JWT 接口安全示例:
1. 首先需要安装 JWT 扩展包,如果使用 composer 可以在命令行中输入 "composer require firebase/php-jwt" 来安装。
2. 生成 JWT 令牌:
```
<?php
require_once "vendor/autoload.php";
use \Firebase\JWT\JWT;
$secret_key = "YOUR_SECRET_KEY";
$issuer_claim = "THE_ISSUER";
$audience_claim = "THE_AUDIENCE";
$issuedat_claim = time(); // issued at
$notbefore_claim = $issuedat_claim + 10; //not before in seconds
$expire_claim = $issuedat_claim + 60; // expire time in seconds
$token = array(
"iss" => $issuer_claim,
"aud" => $audience_claim,
"iat" => $issuedat_claim,
"nbf" => $notbefore_claim,
"exp" => $expire_claim,
"data" => array(
"user_id" => "1",
"user_name" => "John Doe",
)
);
$jwt = JWT::encode($token, $secret_key);
echo $jwt;
```
3. 验证 JWT 令牌:
```
<?php
require_once "vendor/autoload.php";
use \Firebase\JWT\JWT;
$secret_key = "YOUR_SECRET_KEY";
$jwt = "YOUR_JWT_TOKEN";
try {
$decoded = JWT::decode($jwt, $secret_key, array('HS256'));
print_r($decoded);
} catch (\Firebase\JWT\ExpiredException $e) {
echo json_encode(array(
"status" => $e->getStatusCode(),
"message" => $e->getMessage()
));
} catch (\Firebase\JWT\SignatureInvalidException $e) {
echo json_encode(array(
"status" => $e->getStatusCode(),
"message" => $e->getMessage()
));
} catch (\Firebase\JWT\BeforeValidException $e) {
echo json_encode(array(
"status" => $e->getStatusCode(),
"message" => $e->getMessage()
));
} catch (\Firebase\JWT\InvalidArgumentException $e) {
echo json_encode(array(
"status" => $e->getStatusCode(),
"message" => $e->getMessage()
));
} catch (\Exception $e) {
echo json_encode(array(
"status" => $e->getStatusCode(),
"message" => $e->getMessage()
阅读全文