question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Access Token not working

See original GitHub issue

Hi,

My access tokens do not seem to be set correctly. My code is taken from the example (and I have relplaced my id & secret):

var SpotifyWebApi = require('spotify-web-api-node');

var clientId = 'myclientid',
    clientSecret = 'myclientsecret';

var spotifyApi = new SpotifyWebApi({
  clientId : clientId,
  clientSecret : clientSecret
});

spotifyApi.clientCredentialsGrant()
  .then(function(data) {
    console.log('The access token expires in ' + data.body['expires_in']);
    console.log('The access token is ' + data.body['access_token']);
    spotifyApi.setAccessToken(data.body['access_token']);
  }, function(err) {
        console.log('Something went wrong when retrieving an access token', err);
  });

I receive the access token and expiration time, but then if I attempt to search for songs/artists/related artists/anything else, I also receive: { [WebapiError: Unauthorized] name: 'WebapiError', message: 'Unauthorized', statusCode: 401 } even though the setAccessToken has been completed.

Furthermore, unlike the other closed issues similar to this, the searches that I am attempting should not require any scopes as they require no user data.

Any help appreciated 😃

Issue Analytics

  • State:open
  • Created 6 years ago
  • Comments:12

github_iconTop GitHub Comments

3reactions
prashanthrcommented, Sep 24, 2017

Yes. I’ve had success with this. I use a helper in my app to handle the credential flow.

let spotify = new SpotifyWebApi({
  clientId: 'YOUR_CLIENT_ID'
  clientSecret: 'YOUR_CLIENT_SECRET',
  redirectUri: 'YOUR_REDIRECT_URI'
})

  // Can wrap the following methods in a class for ease of use
  async initialize () {
    const token = await getToken()
    spotify.setAccessToken(token)
  }

  async refreshToken () {
    const token = await getRefreshToken()
    spotify.setAccessToken(token)
  }

  async getToken () {
    const result = await spotify.clientCredentialsGrant()
    return result.body.access_token
  }
  
  async getRefreshToken () {
    const result = await spotify.refreshAccessToken()
    return result.body.access_token
  }

  async useApi () {
    // initialize or refreshToken as desired
   await spotify.initialize()
    // use api 
    await spotify.search(....)
  }
2reactions
prashanthrcommented, Jan 27, 2021

@SnowPrimate You’re welcome! Yes that is the right idea. To build a completely stateless application that does what you want when you run it or on schedule, you’ll need to save your refresh token once and inject it into your app or program on start/whenever it runs. Possible options to store this are:

  • in an environment variable
  • a file
  • or in a database that can be read from on startup

Here’s the general idea

  1. On start, load an access token and refresh token from your preferred storage source (assuming you’ve done the credentials grant manually once)
  2. Create a SpotifyWebApi instance (using this library) aka let instance = new SpotifyWebApi({...})
  3. Execute a test request to the Spotify API (you can use any simple API call, even a search)
  4. If you get a 401, refresh the token by calling instance.refreshAccessToken() and set the access token on the SpotifyWebApi instance instance.setAccessToken(access_token). Else proceed to next step on a 2xx response.
  5. Do what you need to do by calling APIs to load up your playlist. Remember to batch your requests by limiting to 100 as you can’t fetch more than 100 results in a single API call.
  6. Lifecycle end - Your program ends but when it starts up again the access token would have expired, but luckily your refresh token hasn’t so it will repeat from step 1 successfully.

Refs:

Read more comments on GitHub >

github_iconTop Results From Across the Web

Personal Access Token in Github not working - Stack Overflow
I have a private repository that I have a dependency on, using https://github.com... in my package.json. I have ssh set up on my...
Read more >
Help! Personal Access Tokens not working : r/github - Reddit
Hello! I'm attempting to push something to github but I get failed authentications, either cannot find username and password, ...
Read more >
Troubleshooting Invalid Access Tokens - Twilio Support
Verify the Access Token Structure · Uses Unix epoch timestamp · Ensure server system clock not skewed · TTL cannot be greater than...
Read more >
Oauth/token not working - Auth0 Community
My oauth/token flow does not work. When I try to authenticate with valid user and password, I get a strange response from the...
Read more >
Troubleshooting OAuth App access token request errors
To solve this error, make sure you have the correct credentials for your OAuth App. Double check the client_id and client_secret to make...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found