Usage of state for redirects
  • 21 Jun 2024
  • 1 Minute to read
  • Dark
    Light
  • PDF

Usage of state for redirects

  • Dark
    Light
  • PDF

Article summary

Redirect users to specific URI after sign in using State parameter

The redirect_uri parameter is only meant as the fixed OAuth callback endpoint, not for forwarding the user to a dynamic URI in your application after authentication.

For that you must store the application state parameter before you redirect users to authenticate so that you can redirect them to a URL. For example, if a user intends to access a protected page in your application, and that action triggers the request to authenticate, you can store that URL to redirect the user back to their intended page after the authentication finishes.

Use the state parameter to lookup and restore the previous state of your application. Generate and store a nonce locally (cookies/session/localstorage), along with any desired state data (like the redirect URL). Use the nonce as a state in the protocol message. If the returned state matches the stored nonce, accept the OAuth message and fetch the corresponding state data from storage.

  1. Generate the nonce that you will use to protect against CSRF attacks as explained before. Store the nonce locally, using it as the key to store all the other application states like the URL where the user intended to go. For example:

{
        "xyzABC123" : {
          redirectUrl: '/protectedResource',
          expiresOn: [...]
        }
    }
              
  1. Authenticate the user, sending the generated nonce as the state.

  2. As part of the callback processing and response validation, verify that the state returned matches the nonce stored locally. If it does, retrieve the rest of the application state (like the redirectUrl).

  3. Once you complete the callback processing, redirect the user to the URL previously stored.

Again, how you store the nonce and the URL or other information pertinent to the application state depends on your application's type. It can be local storage in single-page or native apps or a cookie in a regular web app.

Alternative method

  1. Generate and store a nonce locally.

  2. Encode any desired state (like the redirect URL) along with the nonce in a protected message (that will need to be encrypted/signed to avoid tampering).

  3. In the response processing, unprotect the message, getting the nonce and other properties stored.

  4. Validate that the included nonce matches what was stored locally and, if so, accept the OAuth message.


Was this article helpful?

Changing your password will log you out immediately. Use the new password to log back in.
First name must have atleast 2 characters. Numbers and special characters are not allowed.
Last name must have atleast 1 characters. Numbers and special characters are not allowed.
Enter a valid email
Enter a valid password
Your profile has been successfully updated.