php单页面使用jwt

index.html

root@tr-desktop:/www/wwwroot/troa/webAPI/public/jwt# cat -n index.html
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>JWT POST Request</title>
7 </head>
8 <body>
9
10 <h1>Send POST Request with JWT</h1>
11
12 <!-- Button to trigger sending the POST request -->
13 <button id="sendRequestButton">Send POST Request</button>
14
15 <script>
16 // Sample JWT (replace this with your actual token or get it dynamically)
17 const url = new URL(window.location.href); // 创建 URL 对象
18 const jwtToken = url.searchParams.get('token'); // 获取 name 参数
19 // URL of the API endpoint to send the POST request to
20 const apiUrl = "http://csoa.torealize.work/webAPI/public/jwt/validJwt.php";
21
22 // Data to send with the POST request (as an example)
23 const requestData = {
24 name: "John Doe",
25 age: 30
26 };
27 // Attach event listener to the button
28 document.getElementById("sendRequestButton").addEventListener("click", () => {
29 sendPostRequest();
30 });
31 // Function to send the POST request with JWT in the Authorization header
32 function sendPostRequest() {
33 fetch(apiUrl, {
34 method: 'POST',
35 headers: {
36 'Content-Type': 'application/json',
37 'Authorization': `Bearer ${jwtToken}` // Sending JWT in the Authorization header
38 },
39 body: JSON.stringify(requestData) // Convert the data object to a JSON string
40 })
41 .then(response => {
42 if (!response.ok) {
43 throw new Error('Network response was not ok');
44 }
45 return response.json(); // Parse the response as JSON
46 })
47 .then(data => {
48 console.log('Success:', data); // Handle the success response
49 })
50 .catch(error => {
51 console.error('Error:', error); // Handle any errors
52 });
53 }
54 </script>
55 </body>
56 </html>

生成jwt

root@tr-desktop:/www/wwwroot/troa/webAPI/public/jwt# cat -n toJwt.php
1 <?php
2 require_once 'vendor/autoload.php';
3 use \Firebase\JWT\JWT;
4 use \Firebase\JWT\Key;
5 // 设置密钥
6 $key = "your_secret_key";
7 // 生成 JWT Token
8 function generateJWT($userId) {
9 global $key;
10 $issuedAt = time();
11 $expirationTime = $issuedAt + 60; // jwt有效期秒
12 $payload = [
13 "iss" => "your-app-name",
14 "iat" => $issuedAt,
15 "exp" => $expirationTime,
16 "user_id" => $userId
17 ];
18
19 return JWT::encode($payload, $key, 'HS256');
20 }
21 $userId = 123; // 假设用户 ID 为 123
22 $jwt = generateJWT($userId);
23 echo $jwt;

校验jwt

root@tr-desktop:/www/wwwroot/troa/webAPI/public/jwt# cat -n validJwt.php
1 <?php
2 require_once 'vendor/autoload.php';
3 use \Firebase\JWT\JWT;
4 use \Firebase\JWT\Key;
5 // 设置密钥
6 $key = "your_secret_key";
7 // 验证 JWT Token
8 function validateJWT($jwt) {
9 global $key;
10 try {
11 //解析
12 $decoded = JWT::decode($jwt, new Key($key, 'HS256'));
13 //$decoded = JWT::decode($jwt, $key);
14 return (array) $decoded;
15 } catch (Exception $e) {
16 return null; // 如果验证失败,返回 null
17 }
18 }
19 $headers = getallheaders();
20 if (isset($headers['Authorization'])) {
21 $authorizationHeader = $headers['Authorization'];
22 // Authorization header is in the format "Bearer {token}"
23 list($type, $token) = explode(" ", $authorizationHeader, 2);
24 if (strcasecmp($type, 'Bearer') === 0) {
25 //echo "Token: " . $token;
26 }
27 }
28 // 获取原始 POST 数据
29 $jsonData = file_get_contents('php://input');
30
31 // 将 JSON 数据转换为 PHP 数组或对象
32 $data = json_decode($jsonData, true); // true 表示转换为关联数组,false 表示转换为对象
33
34 if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
35 // 如果 JSON 解码失败
36 echo "Invalid JSON data.";
37 } else {
38 // 处理 JSON 数据
39 echo "<pre>";
40 print_r($data);
41 echo "</pre>";
42 }
43 // 在后续请求中验证 Token
44 $decoded = validateJWT($token);
45 if ($decoded) {
46 echo "User ID: " . $decoded['user_id']; // 用户 ID
47 } else {
48 echo "Invalid or expired token.";
49 }
50
51

jwt.php

root@tr-desktop:/www/wwwroot/troa/webAPI/public/jwt# cat -n jwt.php
1 <?php
2 require_once 'vendor/autoload.php';
3 use \Firebase\JWT\JWT;
4 use \Firebase\JWT\Key;
5 // 设置密钥
6 $key = "your_secret_key";
7 // 生成 JWT Token
8 function generateJWT($userId) {
9 global $key;
10 $issuedAt = time();
11 $expirationTime = $issuedAt + 60; // jwt有效期秒
12 $payload = [
13 "iss" => "your-app-name",
14 "iat" => $issuedAt,
15 "exp" => $expirationTime,
16 "user_id" => $userId
17 ];
18
19 return JWT::encode($payload, $key, 'HS256');
20 }
21 // 验证 JWT Token
22 function validateJWT($jwt) {
23 global $key;
24 try {
25 //解析
26 $decoded = JWT::decode($jwt, new Key($key, 'HS256'));
27 //$decoded = JWT::decode($jwt, $key);
28 return (array) $decoded;
29 } catch (Exception $e) {
30 return null; // 如果验证失败,返回 null
31 }
32 }
33 // 登录时生成 Token
34 $userId = 123; // 假设用户 ID 为 123
35 $jwt = generateJWT($userId);
36 // 在后续请求中验证 Token
37 //$jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ5b3VyLWFwcC1uYW1lIiwiaWF0IjoxNzMwNzc0NDI0LCJleHAiOjE3MzA3NzQ0ODQsInVzZXJfaWQiOjEyM30.VBSDVPheSm6MKx2wuYuY1t1eFOrW1dCkx_JL-SqW4jY"; // 前端传递的 JWT
38 $decoded = validateJWT($jwt);
39 if ($decoded) {
40 echo "User ID: " . $decoded['user_id']; // 用户 ID
41 } else {
42 echo "Invalid or expired token.";
43 }

root@tr-desktop:/www/wwwroot/troa/webAPI/public/jwt# cat dejwt.php
<?php

// 解码 Base64Url
function base64url_decode($data) {
$data = strtr($data, '-_', '+/');
$data = base64_decode($data);
return $data;
}

// JWT 解码
function jwt_decode($jwt) {
// 分割 JWT
$parts = explode('.', $jwt);

if (count($parts) !== 3) {
throw new Exception("Invalid JWT format");
}

// 解码 header
$header = json_decode(base64url_decode($parts[0]), true);

// 解码 payload
$payload = json_decode(base64url_decode($parts[1]), true);

// 由于签名不能被解码,只返回头部和载荷
return [
'header' => $header,
'payload' => $payload
];
}

// 示例 JWT
$jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.cbG00DFv7-3bp-q5cHWoUwAH4DKuxJWxu5_1gq7i-Ps";

// 解码 JWT
try {
$decoded = jwt_decode($jwt);
echo "Header:\n";
print_r($decoded['header']);
echo "Payload:\n";
print_r($decoded['payload']);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}

?>

    A+
发布日期:2024年11月05日  所属分类:php

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: