Handling the Callback

After the user authenticates, they are redirected back to your application with an authorization code.

Steps:

  1. Retrieve Authorization Code and State: Extract these from the query parameters.

  2. Verify State: Ensure the state matches the one you generated earlier.

  3. Exchange Authorization Code for Tokens: Send a POST request to the token endpoint to exchange the authorization code for ID, access, and refresh tokens.

Example Callback Handling:

const params = new URLSearchParams(window.location.search)
const code = params.get('code')
const state = params.get('state')

if (state !== savedState) {
  throw new Error('Invalid state')
}

const codeVerifier = localStorage.getItem('code_verifier')
const body = new URLSearchParams({
  grant_type: 'authorization_code',
  code: code,
  redirect_uri: redirectUri,
  client_id: clientId,
  code_verifier: codeVerifier,
})

const response = await fetch(tokenEndpoint, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: body.toString(),
})

const tokenResponse = await response.json()
localStorage.setItem('access_token', tokenResponse.access_token)
localStorage.setItem('refresh_token', tokenResponse.refresh_token)
localStorage.setItem('id_token', tokenResponse.id_token)

Token Request Parameters

ParameterDescription

grant_type

The type of grant being requested. For authorization code flow, use authorization_code.

code

The authorization code received from the authorization endpoint.

redirect_uri

The URI to which the response will be sent. It must match the redirect URI registered with the client.

client_id

The client ID you obtained during client registration.

code_verifier

The PKCE code verifier.

Example Token Request Body

grant_type=authorization_code&
code=AUTHORIZATION_CODE&
redirect_uri=http://localhost:3000/callback&
client_id=YOUR_CLIENT_ID&
code_verifier=CODE_VERIFIER

Token Response Fields

FieldDescription

access_token

The token that can be used to access protected resources.

id_token

A JWT that contains user identity information.

refresh_token

A token that can be used to obtain new access tokens.

token_type

The type of token issued. Typically Bearer.

expires_in

The duration in seconds for which the access token is valid.

Example Token Response

{
  "access_token": "ACCESS_TOKEN",
  "id_token": "ID_TOKEN",
  "refresh_token": "REFRESH_TOKEN",
  "token_type": "Bearer",
  "expires_in": 3600
}

Last updated

Feedback

Docs

© 2023 -> ♾️