#JWT 验证指南(使用公钥)

#概述

本指南介绍了如何使用公共验证 JSON Web 令牌 (JWT) 钥匙。
JWT 验证确保令牌有效并由受信任的人签名 发行人。


#步骤

#1. 获取公钥


#2. 获取 JWT


#3. 验证 JWT


#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);

#注释