#JWT 驗證指南(使用公鑰)
#概述
本指南介紹如何使用公共驗證 JSON Web 令牌 (JWT)
鑰匙。
JWT 驗證確保令牌有效並由受信任的人簽名
發行人。
#步驟
#1. 取得公鑰
從此處檢索公鑰
以 PEM 格式 提取公鑰。
#2. 取得 JWT
Authorization標頭中應該有一個 JWT 字串,不含Bearer前綴eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...
#3. 驗證 JWT
- 使用公鑰驗證令牌簽署。
- 過程確保:
- 令牌的簽名有效。
- 令牌尚未過期。
iss、aud和其他聲明是正確的。permissions聲明與 API 規格相符
#4. 驗證範例(使用 curl + openssl)
# Example: Decode JWT header and payload
TOKEN="eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..."
HEADER=$(echo $TOKEN | cut -d '.' -f1 | base64 --decode)
PAYLOAD=$(echo $TOKEN | cut -d '.' -f2 | base64 --decode)
echo "Header: $HEADER"
echo "Payload: $PAYLOAD"
# Verify signature manually using openssl
# (Assumes you have the public key saved as public.pem)
SIGNATURE=$(echo $TOKEN | cut -d '.' -f3 | tr '_-' '/+' | base64 -d)
DATA=$(echo -n $(echo $TOKEN | cut -d '.' -f1-2 --output-delimiter='.'))
echo -n $DATA | openssl dgst -sha256 -verify public.pem -signature <(echo -n "$SIGNATURE")
#5. 通用驗證庫
如果編碼,請使用標準 JWT 函式庫: - Node.js: jsonwebtoken -
Python: pyjwt - Go: golang-jwt/jwt/v5 - Java:
nimbus-jose-jwt
Node.js 中的範例:
const jwt = require("jsonwebtoken");
const fs = require("fs");
const publicKey = fs.readFileSync("public.pem");
const token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...";
const decoded = jwt.verify(token, publicKey, { algorithms: ["RS256"] }); // get algorithms from jwks.json
console.log(decoded);
#註釋
- 請務必驗證
exp、iss、aud和permissions聲明。 - 永遠不要相信未簽署或「無」演算法令牌。
- 取得公鑰時使用HTTPS。