使用Spotify-web-api-node生成身份验证令牌 [英] Using spotify-web-api-node to generate an authentication token

查看:12
本文介绍了使用Spotify-web-api-node生成身份验证令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用NodeJS的新手,我正在做一个项目,在这个项目中,我可以通过搜索一次添加一首歌来创建自定义播放列表。我已经能够让代码来完成搜索和获取正确的ID,但是当我试图添加到播放列表时,我得到了一个关于范围错误的错误。长话短说,我做的身份验证类型是错误的。

因此,我仔细阅读了Spotify-web-api-node文档,但在生成授权url和获取响应之间感到困惑,然后另一种方法使用该响应来获取授权令牌。我不确定是否有其他我看不到的方法发出请求,或者我只是应该通过正常的节点方法发出常规请求。

我使用的代码很像是从以下链接(https://github.com/thelinmichael/spotify-web-api-node#authorization)复制粘贴而来的,其中第二个框的标题为"以下使用硬编码的授权码..."是我迷路的地方..。我需要从响应中获取代码,但我不确定如何发送请求才能获得响应,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样式的按钮,上面写着登录此处。该按钮链接到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网站上的身份验证和授权流程(count ts.spotify.com/)。但是,当他们完成此流程后,Spotify会将他们定向到您在createAuthorizeURL中提供的相同reDirect_uri,例如https://www.jd.example.com/callback

这意味着您的Web服务器(例如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);
    }
  });
});

希望这能有所帮助!

这篇关于使用Spotify-web-api-node生成身份验证令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆