Course contentsShow
← Web Development
Lesson 1621 of 2,98229. Web Authentication PatternsFree lesson

Redirect URIs and Callback Handling

Managing OAuth callbacks, extracting authorization codes, and handling redirect URI configuration.

Redirect URIs and Callback Handling

What you'll learn: How OAuth providers send authorization codes back to your application through redirect URIs and how to handle them securely.

The Redirect URI Concept

When a user completes OAuth authorization on a provider's site (like "Sign in with Google"), they need to get back to your application. The redirect URI (also called callback URL) is the exact address where the OAuth provider will send the user—along with an authorization code you'll exchange for tokens.

Think of it like giving someone your return address before they mail you something important. If the address is wrong or unrecognized, the package (authorization code) never arrives.

Configuring Redirect URIs

You must register your redirect URIs with the OAuth provider beforehand:

Registered in OAuth provider dashboard:
https://yourapp.com/auth/callback
http://localhost:3000/auth/callback  (for development)

The provider validates that incoming redirect requests match exactly—including protocol (https), domain, port, and path. A mismatch blocks the authorization.

Handling the Callback

When the user returns to your redirect URI, the OAuth provider appends query parameters:

https://yourapp.com/auth/callback?code=ABC123&state=xyz789

Your callback handler must:

  1. Extract the authorization code from the code parameter
  2. Verify the state parameter matches what you sent (prevents CSRF attacks—you learned about this in session management)
  3. Exchange the code for tokens by making a server-side request to the provider's token endpoint
  4. Handle errors if the user denied permission (?error=access_denied)

Never expose this code exchange in frontend JavaScript—it requires your client secret, which must stay server-side.

Key Takeaway: Redirect URIs are the secure "return address" for OAuth flows; always register them exactly, validate the state parameter, and handle code extraction server-side to prevent security vulnerabilities.