sherlock
sherlock

Reputation: 627

NodeJS + Passport, retrieving an access token (Spotify API)

I'm learning Node.js, and writing a very simple web app using the Spotify API (creating a playlist).

Specifically, I've been using the passport-spotify package, and used the example provided as a starting point.

I've been able to make normal API calls within the app just fine, because they don't require any user authentication, however I now need to make a request and provide an access token.

My previous calls have obviously been pretty simple ajax requests in the public scripts of the app, but now that I require the access token, I've hit a bit of a roadblock.

I've thought of/attempted two methods so far, and they are as follows:

Forgive my lack of knowledge in this area - it's my first time delving into back-end development and OAuth. Retrieving an access token seems like something that should be easy, so maybe I'm going about it all the wrong way.

Thanks for reading!

UPDATE IN CASE ANYONE HAS THE SAME PROBLEM: I solved the problem by creating a global variable for the access token, assigning it when it passes through the app, and then creating a cookie from it in the callback phase - app.get('/callback')... in the example I mentioned above. I can then read the token in my public javascript through that cookie.

I should say that I am not sure if this is the best (or safest) method, but it has worked for my purposes. I assume making a global variable for the token isn't good, but I'm not sure.

If anyone sees my solution and notices an issue or better method, I am still interested to hear about that.

Upvotes: 3

Views: 3523

Answers (1)

Neil Devas
Neil Devas

Reputation: 23

The callback function for the passport configuration gets called with an access token and a refresh token.

passport.use(
new SpotifyStrategy(
    {
      clientID: client_id,
      clientSecret: client_secret,
      callbackURL: 'http://localhost:8888/auth/spotify/callback'
    },
    function(accessToken, refreshToken, expires_in, profile, done) {
      User.findOrCreate({ spotifyId: profile.id }, function(err, user) {
        return done(err, user);
      });
    }
  )
);

You can store that access token and refresh token in a database. If your app uses the authorization code flow, you can find or create a User in your database, and store the two tokens inside that user object. Then you can pick off this token and use it in your requests.

I would suggest taking a look at https://github.com/thelinmichael/spotify-web-api-node. This is a wrapper around the Spotify API, where you can pass in your tokens and the wrapper will automatically include your access token as a header on each request you make.

Upvotes: 1

Related Questions