Getting Access Token

Now that your user is redirected back to your app, you will get code in the URL (and state if you defined it), which you will exchange for an Access Token.

To do an exchange, it's straightforward. You will need to call one API (see Implementation page for URLs).

First, get the code from the URL. You can do that with a simple search params get.

const url = new URL(window.location.url)
const code = url.searchParams.get('code')

Now we will call an API with this info.

const verifier = 'my secret text'
const tokenUrl = 'http://api-sandbox.edgetag.io/v1/oauth-app/client/token'

const body = new URLSearchParams({
  code,
  code_verifier: verifier,
  grant_type: 'authorization_code',
})

const response = await fetch(tokenUrl, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    Authorization: `Basic ${btoa(clientId + ':' + clientSecret)}`,
  },
  body
})

Let's look at the code to see what we are doing. We are adding three parameters to the URL:

1) code: you get that from the URL

2) code_verifier: this is the one that you hashed before you for the redirect. You need to pass it here in plain text

3) grant_type: this needs to be authorization_code

Next, we need to add an Authorization header. This is a basic authorization with a client ID and secret, base64-encoded.

Request is GET . If the request is successful, you will get the following response:

Our access token expires every two hours (7200 seconds). You will need to use refresh_token to get a new token after two hours. We will learn how to do it on the next page. access_token is already a valid token that you can use for the next two hours.

Last updated

Was this helpful?