---
title: Validate OAuth Redirect URIs Exactly
impact: CRITICAL
impactDescription: prevents authorization code theft by ensuring tokens are only sent to verified client URLs
tags: oauth, redirect, uri, validation, security, kotlin
---

## Validate OAuth Redirect URIs Exactly

When acting as an OAuth 2.0 Identity Provider (IdP) or using an external one, the `redirect_uri` parameter must be validated against an exact, pre-registered whitelist. Loose validation (like prefix matching or regex) can be bypassed by attackers to steal secrets.

**Incorrect (partial or loose validation):**

```kotlin
// VULNERABLE: Substring matching
if (redirectUri.contains("sun-asterisk.vn")) {
    // Attack: https://attacker.com?sun-asterisk.vn
}

// VULNERABLE: Prefix matching without trailing slash
if (redirectUri.startsWith("https://app.sun-asterisk.vn")) {
    // Attack: https://app.sun-asterisk.vn.attacker.com/callback
}
```

**Correct (exact match against registered URIs):**

```kotlin
private val ALLOWED_REDIRECT_URIS = setOf(
    "https://auth.sun-asterisk.vn/callback",
    "https://mobile.sun-asterisk.vn/oauth/success"
)

fun validateRedirectUri(inputUri: String) {
    // MUST perform a case-sensitive exact string comparison
    if (!ALLOWED_REDIRECT_URIS.contains(inputUri)) {
        throw SecurityException("Unauthorized redirect_uri: $inputUri")
    }
}

// If acting as an OAuth Provider (Spring Security Auth Server)
@Configuration
class SecurityConfig {
    @Bean
    fun registeredClientRepository(): RegisteredClientRepository {
        return InMemoryRegisteredClientRepository(
            RegisteredClient.withId("client-id")
                .redirectUri("https://app.example.com/login/oauth2/code/gateway") // Exact
                .build()
        )
    }
}
```

**Security Requirements:**
1.  **Exact Matching:** Use `equals()` or Set `contains()`. Never use `startsWith` or `contains`.
2.  **No Wildcards:** Do not support wildcards in redirect URIs.
3.  **HTTPS Only:** In production, only allow `https://` (except for specific localhost dev cases if strictly necessary).
4.  **Pre-Registration:** The client must register their redirect URIs before they can initiate any OAuth flows.

**Tools:** Spring Security OAuth2, OWASP ZAP, Manual Audit, Penetration Testing
