Announcements

Help Wizard

Step 1

NEXT STEP

FAQs

Please see below the most popular frequently asked questions.

Loading article...

Loading faqs...

VIEW ALL

Ongoing Issues

Please see below the current ongoing issues which are under investigation.

Loading issue...

Loading ongoing issues...

VIEW ALL

401 Error with seemingly working access token

401 Error with seemingly working access token

I am using the following code to get an access token, and the final post request returns a status code of 200 and when I print out the access token it looks good. However as soon as I try to use the access token I get a 401 Unauthroized error. I have been slamming my head against the wall looking everywhere for what I am doing wrong and can't find it, please let me know if you have any tips.

app.get('/spotifylogin', function(req, res) {

  let url = AUTHORIZE;
  url += "?client_id=" + client_id;
  url += "&response_type=code";
  url += "&redirect_uri=" + redirect_uri;
  url += "&show_dialog=true";
  url += "&scope=user-top-read";
  res.redirect(url); // Show Spotify's authorization screen

});

app.get('/callback', function(req, res) {

  const authConfig = {
    headers: {
        Authorization: `Basic ${Buffer.from(
            `${client_id}:${client_secret}`
        ).toString('base64')}`,
      }
  };
 
  axios.post(
      'grant_type=client_credentials',
      authConfig
  ).then(data => {
    access_token = data.data.access_token;
    //refresh_token = data.refresh_token;
    //localStorage.setItem('refresh_token',refresh_token);
    spotify_linked = true;
    res.redirect('/toptracks');
  })
  .catch(error => {
    console.log(error);
  })
});

This is the function I am calling with the access token which gives me the 401 error.

async function getProfile(accessToken) {
  const response = await fetch('https://api.spotify.com/v1/me', {
    headers: {
      Authorization: 'Bearer ' + accessToken
    }
  });

  const data = await response.json();
  console.log(data);
}
Reply
1 Reply

It seems you're using the wrong grant type for the Spotify API authentication. Instead of grant_type=client_credentials, for user authentication, you should use grant_type=authorization_code. This change allows you to exchange the authorization code for an access token and refresh token.

XimzendSpotify Star
Help others find this answer and click "Accept as Solution".
If you appreciate my answer, maybe give me a Like.
Note: I'm not a Spotify employee.

Suggested posts

Type a product name