Node.js Express Spotify API 在会话中保存

Node.js Express Spotify API save in session

使用 spotify-web-api-node 将 Spotify API 集成到 Nodejs Express 网络应用程序时出现问题。应该如何处理多个并发用户请求?通过身份验证步骤后,用户收到 access_token,每个用户都不同。每个请求都可以有一个会话,例如使用 express-session 因为 access_token 对于每个经过身份验证的用户都是唯一的。奇怪的是,我在描述和示例 https://www.npmjs.com/package/spotify-web-api-node where spotify-web-api-node is used. How is that possible to use global variable without session? Would it make full mess among separate user requests or I'm missing something? I guess that the access_token would be always replaced with latest authenticated user. Another usage example is here https://github.com/thelinmichael/spotify-web-api-node 中找不到正确使用会话的示例,尽管它也建议使用一个全局实例。

解决方案是在会话存储中成功验证后存储 access_tokenrefresh_token,而不是在调用 Spotify 之前 API 端点从现在开始为当前用户设置两个令牌会话:

成功验证后在会话中保存令牌:

app.get('/login', (req,res) => {
  var scopes = [ ... ]
  var authUrl = spotifyApi.createAuthorizeURL(scopes)
  res.redirect(authUrl+"&show_dialog=true")
})

app.get('/callback', async (req, res) => {
  const { code } = req.query
  try {
    var data = await spotifyApi.authorizationCodeGrant(code)
    const { access_token, refresh_token } = data.body
    spotifyApi.setAccessToken(access_token)
    spotifyApi.setRefreshToken(refresh_token)

    req.session.spotifyAccount = { access_token, refresh_token }

    res.redirect('...')
  } catch(err) {
    res.send(`error ${err}`)
  }
});

app.get('/userinfo', async (req,res) => {
  try {
    spotifyApi.setAccessToken(req.session.spotifyAccount["access_token"])
    spotifyApi.setRefreshToken(req.session.spotifyAccount["refresh_token"])
    var result = await spotifyApi.getMe()
    console.log(result.body);
    res.status(200).send(result.body)
  } catch (err) {
    res.status(400).send(err)
  }
});

因为 access_token 只是标识任何 API 请求的标识键,确保为当前用户调用 API 端点。这种技术可以防止混乱和混乱,因此每个用户只能查看和操作他的数据。