# OAuth2令牌端点返回HTTP 400：invalid_grant，错误描述为'无效的授权码'

- **ID:** `security/oauth2-token-endpoint-http-400`
- **领域:** security
- **类别:** protocol_error
- **错误码:** `OAUTH2_INVALID_GRANT`
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

令牌交换中使用的授权码无效、已过期或已被使用，通常是由于多个请求尝试使用同一个授权码的竞态条件，或者该授权码是为不同的客户端ID签发的。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Spring Security 6.0.0 | active | — | — |
| Passport.js 0.6.0 | active | — | — |
| Okta SDK 1.0.0 | active | — | — |
| Express OAuth2 Server 3.0.0 | active | — | — |

## 解决方案

1. ```
   确保授权码只使用一次。如果令牌交换因网络错误失败，不要自动使用相同的授权码重试；而是将用户重定向到重新认证。
   ```
2. ```
   检查令牌请求中使用的客户端ID和重定向URI是否与授权请求中使用的完全匹配。不匹配会导致授权码被拒绝。
   ```
3. ```
   如果授权码被后台任务或多个工作进程消费，添加锁或状态机以确保同一时间只有一个请求可以交换该授权码。
   ```

## 无效尝试

- **** — Retrying the token exchange immediately with the same authorization code will always fail because the code is single-use and has been consumed on the first attempt. (100% 失败率)
- **** — Increasing the authorization code expiration time on the server can help with delays but does not fix the root cause if the code is being reused or mismatched. (40% 失败率)
- **** — Clearing browser cookies and restarting the flow may work but is not a systematic fix; it only masks the issue for the user and doesn't address the underlying client-side bug. (50% 失败率)
