# OAuth2 token endpoint returned HTTP 400: invalid_grant with error_description 'Invalid authorization code'

- **ID:** `security/oauth2-token-endpoint-http-400`
- **Domain:** security
- **Category:** protocol_error
- **Error Code:** `OAUTH2_INVALID_GRANT`
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

The authorization code used in the token exchange is invalid, expired, or has already been used, often due to a race condition where multiple requests attempt to use the same code or the code was issued for a different client ID.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 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 | — | — |

## Workarounds

1. **Ensure the authorization code is used exactly once. If the token exchange fails due to a network error, do not automatically retry with the same code; instead, redirect the user to re-authenticate.** (90% success)
   ```
   Ensure the authorization code is used exactly once. If the token exchange fails due to a network error, do not automatically retry with the same code; instead, redirect the user to re-authenticate.
   ```
2. **Check that the client ID and redirect URI used in the token request exactly match those used in the authorization request. Mismatches cause the code to be rejected.** (80% success)
   ```
   Check that the client ID and redirect URI used in the token request exactly match those used in the authorization request. Mismatches cause the code to be rejected.
   ```
3. **If the code is being consumed by a background job or multiple workers, add a lock or a state machine to ensure only one request can exchange the code at a time.** (75% success)
   ```
   If the code is being consumed by a background job or multiple workers, add a lock or a state machine to ensure only one request can exchange the code at a time.
   ```

## Dead Ends

- **** — 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% fail)
- **** — 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% fail)
- **** — 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% fail)
