【问题标题】:Node.js Express Spotify API save in sessionNode.js Express Spotify API 保存在会话中
【发布时间】:2020-05-22 09:25:42
【问题描述】:

使用spotify-web-api-node 将 Spotify API 集成到 Nodejs Express Web 应用程序时出现问题。应该如何处理多个同时的用户请求?通过身份验证步骤后,用户收到access_token,每个用户都不同。每个请求都可以有一个会话,例如使用express-session,因为access_token 对于每个经过身份验证的用户都是唯一的。奇怪的是,我在描述和示例https://www.npmjs.com/package/spotify-web-api-node 中找不到正确使用会话的示例,其中使用了spotify-web-api-node。没有会话如何使用全局变量?它会在单独的用户请求之间造成混乱还是我遗漏了什么?我猜access_token 总是会被最新的经过身份验证的用户替换。另一个使用示例在这里https://github.com/thelinmichael/spotify-web-api-node,尽管它也建议使用一个全局实例。

【问题讨论】:

    标签: node.js express spotify session-state


    【解决方案1】:

    解决方案是在成功验证后将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 端点。这种技术可以防止混乱和混乱,因此每个用户只能查看和操作他的数据。

    【讨论】:

      猜你喜欢
      • 2012-06-09
      • 2012-12-09
      • 1970-01-01
      • 2012-12-03
      • 2014-12-19
      • 1970-01-01
      • 2018-06-30
      • 2018-10-03
      • 1970-01-01
      相关资源
      最近更新 更多