# OAuth2授权码因redirect_uri开放重定向被拦截

- **ID:** `security/oauth2-authorization-code-interception-via-open-redirect`
- **领域:** security
- **类别:** protocol_error
- **错误码:** `AUTH_CODE_INTERCEPTION`
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

OAuth2授权服务器未严格验证redirect_uri是否与注册白名单匹配，允许攻击者利用开放重定向端点拦截授权码。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| OAuth 2.0 RFC 6749 | active | — | — |
| Spring Security OAuth2 2.3.0 | active | — | — |
| Auth0 Node.js SDK 2.12.0 | active | — | — |
| Okta OIDC Middleware 3.0.0 | active | — | — |

## 解决方案

1. ```
   Strictly validate redirect_uri against an exact, registered whitelist. For example, in Spring Security OAuth2, configure the authorization server to reject any redirect_uri that does not exactly match a registered value:

@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("client1")
            .redirectUris("https://app.example.com/callback")
            .autoApprove(true)
            .scopes("read");
    }
}
   ```
2. ```
   Implement a redirect_uri allowlist in the authorization server that rejects any URI not exactly matching a registered pattern. For example, in a Node.js OAuth2 library:

const allowedRedirectUris = ['https://app.example.com/callback'];
function validateRedirectUri(uri) {
  return allowedRedirectUris.includes(uri);
}
   ```
3. ```
   Use PKCE (Proof Key for Code Exchange) to mitigate authorization code interception. PKCE ensures that even if the code is intercepted, it cannot be exchanged without the original code verifier. Example in Auth0:

const client = new OAuth2Client({
  clientId: 'your-client-id',
  authorizationUri: 'https://auth.example.com/authorize',
  tokenUri: 'https://auth.example.com/token',
  redirectUri: 'https://app.example.com/callback',
  usePKCE: true
});
   ```

## 无效尝试

- **Add HTTPS requirement to redirect_uri without whitelist check** — HTTPS alone does not prevent open redirect attacks; the attacker can still use a valid HTTPS endpoint that redirects to their site. (90% 失败率)
- **Use wildcard patterns in redirect_uri registration (e.g., https://*.example.com/*)** — Wildcards allow attackers to register subdomains or paths they control, bypassing the intent of strict matching. (85% 失败率)
- **Rely on state parameter alone without redirect_uri validation** — The state parameter prevents CSRF but does not protect against authorization code interception via open redirect. (95% 失败率)
