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

Using spotify-web-api-node to generate an authentication token

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

所以我阅读了 spotify-web-api-node 文档,但我在生成授权 url 和获取响应之间迷失了方向,然后由另一种方法使用该响应来获取授权令牌。我不确定是否有另一种我没有看到的方法会发出请求,或者我是否应该通过普通节点方法发出常规请求。

我使用的代码几乎是来自以下 link (https://github.com/thelinmichael/spotify-web-api-node#authorization) 的 copy-paste,其中第二个框带有 header "The below uses a hardcoded authorization code..." 是我迷路的地方......我需要从响应中获取该代码,但我不确定我将如何发送请求以获取响应,createAuthorizeURL 方法似乎使实际url但不发送。

我认为混淆源于 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 风格的按钮,上面写着 Login here。该按钮链接到 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);
    }
  });
});

希望对您有所帮助!