How do I set up a dynamic Allowed Callback URL?

Question: How do I set up a dynamic Allowed Callback URL?

Answer:

If your application has several protected routes that follow a pattern (e.g., https://example.com/users/:user_id), you may want to set up the application’s Allowed Callback URLs in a dynamic way that won’t require hard-coding a long list of URLs.

Wildcards

You can use a wildcard in the subdomain (as long as it follows the guidelines outlined in the documentation). However, to follow OAuth 2.0 Security Best Current Practice, you cannot use a wildcard in the URL path.

For example, you can use https://*.example.com; however, you cannot use https://example.com/*.

Solution - Single Callback URL Using State

Instead of creating a list of callback URLs, you can use a single callback URL (e.g., /callback) that handles the redirect for users.

You can set this up by leveraging the state parameter during authentication:

  1. First, create a random string used as a key to lookup the redirect URL after the user authenticates. You can store the redirect URL using local storage:
localStorage.setItem('randomValue', 'redirectURL');
  1. Pass the random value as the state parameter in the authentication request to Auth0.

  2. Auth0 will redirect the user to your callback route (/callback) along with the same state parameter that you sent in the authentication request. Use the state value to retrieve the redirect URL from local storage:

localStorage.setItem('randomValue');

Auth0 SPA JS Implementation Using appState

If you are using auth0-spa-js (or auth0-react or auth0-angular) then you can implement a single callback URL by using appState:

  1. Include the redirect URL within the appState object when your application calls auth0.loginWithRedirect:
auth0.loginWithRedirect({ appState: { target: 'redirectURL'});
  1. When the user has authenticated and is redirected back to the application, call auth0.handleRedirectCallback() to retrieve the appState:
const appState = await auth0.handleRedirectCallback();

appState.target will contain the redirect URL.

Supporting Documentation:

Documentation: Wildcards for Subdomains, Prevent Attacks and Redirect Users with OAuth 2.0 State Parameters
Community Topic: Allowed Callback URLs ending with a wildcard - #2 by prashantT

2 Likes