# JWT算法混淆：当期望HS256时接受了RS256令牌

- **ID:** `security/oauth2-jwt-algorithm-confusion-rs256-hs256`
- **领域:** security
- **类别:** auth_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

JWT库配置为同时接受RS256（非对称）和HS256（对称）算法，攻击者可以使用公钥作为HMAC密钥对令牌签名，绕过签名验证。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| jsonwebtoken 8.5.1 | active | — | — |
| jjwt 0.11.5 | active | — | — |
| PyJWT 2.8.0 | active | — | — |

## 解决方案

1. ```
   在JWT验证函数中，明确指定允许的算法，并拒绝使用不同算法的任何令牌。例如，在Node.js中：jwt.verify(token, publicKey, { algorithms: ['RS256'] })
   ```
2. ```
   使用默认强制单一算法的库，例如jose（v4+），它需要显式选择算法。
   ```
3. ```
   在调用验证函数之前，添加检查'alg'头是否完全等于预期值的逻辑，否则拒绝。
   ```

## 无效尝试

- **** — Simply disabling HS256 globally breaks legitimate symmetric token use cases in other parts of the system. (40% 失败率)
- **** — Adding a blacklist of known bad keys doesn't address the root cause — the library must enforce a single algorithm per token, not rely on external lists. (60% 失败率)
- **** — Upgrading the JWT library without changing the verification code may not help if the code explicitly passes both algorithms to the verifier. (30% 失败率)
