JSON Web Token 的头部 alg 字段由客户端提交。若服务端未严格锁定预期算法,攻击者可将 alg 改为 none 或从 RS256 降级为 HS256 并使用公钥作为 HMAC 密钥伪造签名,从而越权访问受保护接口。
一、强制校验白名单算法
python
import jwt
ALLOWED_ALGORITHMS = ["RS256"]
def verify_token(token: str, public_key: str) -> dict:
try:
# 显式指定 algorithms 白名单,杜绝 alg=none 与算法混淆
payload = jwt.decode(
token,
public_key,
algorithms=ALLOWED_ALGORITHMS,
options={"require": ["exp", "iss", "sub"]},
)
return payload
except jwt.InvalidAlgorithmError:
raise PermissionError("Unsupported signing algorithm")