Obtain the Authorization Code Access Token
Get the authorization code access token required to access the Spotify API endpoints.
We'll cover the following
As we discussed earlier, for all the endpoints where we access a user's resources, we need to use either the authorization code, the authorization code with PKCE, or the implicit grant flow to get the access token. In this lesson, we’ll learn how to get the access token using the authorization code flow.
Authorization code
The workflow needed to get the authorization code access token is as follows:
First, we need to redirect the user to the Spotify API server by making a call to the base URI https://accounts.spotify.com/authorize
with some query parameters. The user is asked to log in to Spotify using a dialog box.
After the user has logged in, a dialog box will pop up asking the user to accept or deny our grant request.
Once the user accepts our request, we'll receive a code.
Then we’ll make an API call using the base URI https://accounts.spotify.com/api/token
and some query parameters.
Finally, we’ll receive an access token that we can use to access the user-specific endpoints.
Get an access token
It is time to get our access token using the authorization code flow. We'll use the Express app in the widget below to get the token. Click "Run" to see the app in action.
const port = 3000 // Client Keys const CLIENT_ID = "{{CLIENT_ID}}" const CLIENT_SECRET = "{{CLIENT_SECRET}}" // Encoding values for header const required_ids = Buffer.from(CLIENT_ID+':'+CLIENT_SECRET); const encoded = required_ids.toString('base64'); // Spotify URLS const SPOTIFY_AUTH_URL = "https://accounts.spotify.com/authorize" const SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token" // Server-side Parameters const REDIRECT_URI = "{{EDUCATIVE_LIVE_VM_URL}}/callback" const SCOPE = "playlist-read-collaborative playlist-modify-public playlist-modify-private playlist-read-private user-library-read user-library-modify" const RESPONSE_TYPE = "code" const GRANT_TYPE = 'authorization_code' app.get('/', (req, res) => { res.redirect(SPOTIFY_AUTH_URL+'?response_type='+RESPONSE_TYPE+'&client_id='+CLIENT_ID+'&redirect_uri='+REDIRECT_URI+'&scope='+SCOPE+'&show_dialog=TRUE') }) app.get('/callback', (req, res) => { headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic '+encoded } body = {'code': req.query.code, 'redirect_uri': REDIRECT_URI, 'grant_type': GRANT_TYPE} request.post({url:SPOTIFY_TOKEN_URL,headers:headers,form:body}, (err, response, body) => { if (err) { console.log(err); } else if (response.statusCode === 200) { let struct = JSON.parse(body); const access_token=struct.access_token; const refresh_token=struct.refresh_token; console.log(struct); res.set('Content-Type', 'text/html'); res.send('<div><p>access_token: '+access_token+'</p><p>refresh_token: '+refresh_token+'<p></div>'); } else { console.log(response.statusCode); res.json(body) } }); }); app.listen(port, () => { console.log(`Auth app is listening on port ${port}`) })
Once the app is up and running, follow the steps below:
Go to the app URL mentioned under the "Run" button. The
index()
function defined in lines 21–24 makes the API call for the code and redirects to the Spotify API server.Log in if required and accept the code request. A code will be sent to this app after the permission has been granted. Once this app receives the code, the
callback()
function defined in lines 28–39 will request the access token. In response to this request, we'll obtain our access token.Copy the
access_token
and therefresh_token
received in response and save them in the widget below.
Once we’ve saved the tokens, click the "Run" button to check the validity of the access token.
validateToken() //A function that validates the access token
Note: The query parameters for the Authorize and Token endpoints have been discussed in detail in this lesson of the "Appendix" chapter.
Refresh token
The access code provided by the app above is valid for one hour only. We wouldn't want to bother the user after one hour to grant us permission to get a new access token. This is where the refresh_token
that we saved in the above widget plays its role. After the access token has expired, we can call the base URI https://accounts.spotify.com/api/token
with grant_type
set to refresh_token
to get a new access token. The refresh_token
is sent as a query parameter with this request.
Refresh the access token
The code below shows how we can get a new access code using the refresh token. Click the "Run" button to get a new access token.
const endpointUrl = new URL('https://accounts.spotify.com/api/token');const queryParameters = new URLSearchParams({grant_type: 'refresh_token',refresh_token: '{{REFRESH_TOKEN}}'});const required_ids = Buffer.from('{{CLIENT_ID}}:{{CLIENT_SECRET}}');const encoded = required_ids.toString('base64');headerParameters = {'Content-Type': 'application/x-www-form-urlencoded','Authorization': 'Basic '+encoded}const options = {method: 'POST',headers: headerParameters};async function refreshAccessToken() {try {endpointUrl.search = queryParameters;const response = await fetch(endpointUrl, options);printResponse(response);} catch (error) {printError(error);}}refreshAccessToken();
The code is similar to the one we used to obtain the client credential access token. Here are the changes we've made in the code:
Line 1: We update
URL
tohttps://accounts.spotify.com/api/token
.Lines 3–6: We set the query parameters.
Line 17: We set the request type to
POST
.Lines 21–29: We define a function,
refreshAccessToken()
, that calls the defined endpoint and prints the response.
We receive the access token, its type, its validity duration, and its scope, in response.