NodeJS + Passport,如何获取访问令牌(Spotify API)

3

我正在学习Node.js,并使用Spotify API创建一个非常简单的Web应用程序(创建播放列表)。

具体来说,我一直在使用passport-spotify包,并使用提供的example作为起点。

我已经成功地在应用程序中进行了普通API调用,因为它们不需要任何用户身份验证,但是现在我需要发出请求并提供访问令牌。

我的以前的调用显然是在应用程序的公共脚本中进行的,但是现在我需要访问令牌,我遇到了一些问题。

到目前为止,我想到/尝试了两种方法,分别如下:

  • Store the access token that Passport retrieves (and seemingly brushes aside) as a cookie, and then access that cookie in the public javascript like I have been for other API calls. I'm not sure about the security of this method. Either way, I was unable to figure out how to even set it as a cookie, as this requires res.cookie(), and res is not passed into the function.
  • Create a new route that when requested with ajax will trigger a node-based api request, so this way the access token stays hidden. Here below is what I came up with for that. I do get a response which seems to indicate that the idea works, but I don't know how to retrieve the access token.

    app.get('/playlist/:name', function(req, res){
    
    var options = {
      url: 'spotify api link, cannot post without more reputation',
      headers : {
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + accessToken,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name: req.params.name,
        public: false
      })
    };
    
    request.post(options, function(error, response, body){
      console.log(error);
      console.log(response);
      console.log(body);
    })
    
    });
    

对不起,我在这个领域缺乏知识 - 这是我第一次深入研究后端开发和OAuth。检索访问令牌似乎是一件容易的事情,所以也许我正在错误的方向上努力。

谢谢您的阅读!

更新以防有人遇到同样的问题: 我通过创建全局变量来解决了访问令牌的问题,在它通过应用程序时分配它,然后在回调阶段创建一个cookie - 在上面提到的示例中是app.get('/callback')...。然后,我可以通过该cookie在我的公共JavaScript中读取令牌。

我应该说,我不确定这是否是最佳(或最安全)的方法,但它已经适合我的目的。 我假设为令牌创建全局变量并不好,但我不确定。

如果有人看到我的解决方案,并注意到问题或更好的方法,请告诉我,我仍然很感兴趣。

1个回答

1

Passport 配置的回调函数将被调用,其中会传入一个访问令牌和刷新令牌。

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);
      });
    }
  )
);

你可以将访问令牌和刷新令牌存储在数据库中。如果你的应用使用授权码流程,你可以在数据库中查找或创建一个用户,并将这两个令牌存储在该用户对象中。然后,你可以提取此令牌并在请求中使用它。
我建议你看一下https://github.com/thelinmichael/spotify-web-api-node。这是一个Spotify API的包装器,你可以传递你的令牌,包装器将自动在你发出的每个请求中包含你的访问令牌作为标头。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接