使用spotify-web-api-node生成身份验证令牌

时间:2015-01-04 01:35:37

标签: node.js spotify

我是使用nodejs的新手,我正在开发一个项目,我可以通过搜索一次添加一首歌来制作自定义播放列表。我已经能够获取代码来进行搜索并抓取正确的ID,但在尝试添加到播放列表时,我收到有关范围错误的错误。长话短说,我做了错误的身份验证。

所以我读了一下spotify-web-api-node文档,但是我在生成授权URL然后获得响应之间迷路了,然后由另一个方法用来获取授权令牌。我不确定是否有其他方法我没有看到它会提出请求,或者我是否应该通过正常的节点方法执行常规请求。

我使用的代码几乎是来自以下链接(https://github.com/thelinmichael/spotify-web-api-node#authorization)的复制粘贴,其中第二个框带有标题"以下使用硬编码授权代码。 "是我丢失的地方......我需要从响应中获取该代码,但我不确定如何发送请求以获得响应,createAuthorizeURL方法似乎制作实际网址但不发送。

1 个答案:

答案 0 :(得分:7)

我认为混淆源于Authorization Code flow的工作方式,以及我为节点包装器编写文档的方式。 createAuthorizeURL方法的目的是帮助您创建转发用户所需的URL。

来自您链接的同一篇文档:

In order to get permissions, you need to direct the user to our Accounts service. 
Generate the URL by using the wrapper's authorization URL method.

因此,假设用户首先输入您的网站http://www.jd.example.com。它将有一个Spotify样式按钮,上面有登录。该按钮链接到createAuthorizeURL生成的URL。 URL的一个非常重要的部分是redirect_uri查询参数。例如,您将生成的URL看起来像

https://accounts.spotify.com:443/authorize?client_id=5fe01282e44241328a84e7c5cc169165&
response_type=code&redirect_uri=https://www.jd.example.com/callback&
scope=playlist-modify-public

当用户点击该按钮时,他们将通过Spotify网站上的身份验证和授权流程(accounts.spotify.com/)。但是,当他们完成此流程时,Spotify会将它们定向到您在createAuthorizeURL中提供的相同redirect_uri,例如, https://www.jd.example.com/callback

这意味着您的网络服务器(例如Express)需要能够处理对redirect_uri的请求。如果您的Web服务器确实是Express,它可能看起来像这样。

/* Some express.js setup here */
/* Some spotify-web-api-node setup here */

/* Handle authorization callback from Spotify */
app.get('/callback', function(req, res) {

  /* Read query parameters */
  var code  = req.query.code; // Read the authorization code from the query parameters
  var state = req.query.state; // (Optional) Read the state from the query parameter

  /* Get the access token! */
  spotifyApi.authorizationCodeGrant(code)
    .then(function(data) {
      console.log('The token expires in ' + data['expires_in']);
      console.log('The access token is ' + data['access_token']);
      console.log('The refresh token is ' + data['refresh_token']);

      /* Ok. We've got the access token!
         Save the access token for this user somewhere so that you can use it again.
         Cookie? Local storage?
      */

      /* Redirecting back to the main page! :-) */
      res.redirect('/');

    }, function(err) {
      res.status(err.code);
      res.send(err.message);
    }
  });
});

希望这有帮助!

相关问题