当前位置: 首页 > 知识库问答 >
问题:

Nodejs-Spotify API刷新令牌

陆畅
2023-03-14

首先。我以前没有使用过 API。

我的问题是刷新令牌。作为查询参数返回给重定向URI的代码似乎每次都需要手动放入。当我获得该身份验证代码时,下面的代码将为我获取新的访问令牌以及刷新令牌。

我使用的软件包是 spotify-web-api-节点,下面的代码是遵循他们的自述文件的结果。我也尝试过 spotify-oauth-复习器,但我对编码太陌生了,无法弄清楚如何使用它。

我也尝试过在Spotify自己的网站上遵循指南。但我自己似乎无法做到这一点。

希望得到一些指导。谢谢。希望事情很清楚。

 var scopes = ['user-read-private', 'user-read-email', 'playlist-read-private', 'playlist-modify-private'],
      redirectUri = '<redirect uri>',
      clientId = '<client id>',
      clientSecret = '<client secret>',
      state = '<random string>';
    
    var spotifyApi = new SpotifyWebApi({
      redirectUri: redirectUri,
      clientId: clientId,
      clientSecret: clientSecret
    });
    
    // Create the authorization URL
    var authorizeURL = spotifyApi.createAuthorizeURL(scopes, state);
    
    console.log(authorizeURL);
    
    var credentials = {
      clientId: '<client id>',
      clientSecret: '<client secret>',
      redirectUri: '<redirect uri>'
    };
    
    var spotifyApi = new SpotifyWebApi(credentials);
    
    // The code that's returned as a query parameter to the redirect URI
    var code = 'I HAVE TO MANUALLY PUT THIS IN WHEN THE DURATION RUNS OUT';
    
    // Retrieve an access token and a refresh token
    spotifyApi.authorizationCodeGrant(code).then(
      function(data) {
        console.log('The token expires in ' + data.body['expires_in']);
        console.log('The access token is ' + data.body['access_token']);
        console.log('The refresh token is ' + data.body['refresh_token']);
    
        // Set the access token on the API object to use it in later calls
        spotifyApi.setAccessToken(data.body['access_token']);
        spotifyApi.setRefreshToken(data.body['refresh_token']);
      },
      function(err) {
        console.log('Something went wrong!', err);
      }
    );
    
    // clientId, clientSecret and refreshToken has been set on the api object previous to this call.
    spotifyApi.refreshAccessToken().then(
      function(data) {
        console.log('The access token has been refreshed!');
    
        // Save the access token so that it's used in future calls
        spotifyApi.setAccessToken(data.body['access_token']);
      },
      function(err) {
        console.log('Could not refresh access token', err);
      }
    );

编辑:我已经创建了一个工作解决方案,有时间的时候会提交我的代码。希望是今天。

共有2个答案

华景焕
2023-03-14

可以在下面的链接中找到直接来自Spotify的最佳实践身份验证流的信息。它包括详细说明他们希望您如何以及何时发布新访问令牌的刷新令牌的代码片段。

https://developer . Spotify . com/documentation/general/guides/authorization/code-flow/

这是他们建议的endpoint,用于在您检测到访问令牌已过期或您的数据请求因访问令牌过期而失败时刷新令牌。

app.get('/refresh_token', function(req, res) {

  var refresh_token = req.query.refresh_token;
  var authOptions = {
    url: 'https://accounts.spotify.com/api/token',
    headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) },
    form: {
      grant_type: 'refresh_token',
      refresh_token: refresh_token
    },
    json: true
  };

  request.post(authOptions, function(error, response, body) {
    if (!error && response.statusCode === 200) {
      var access_token = body.access_token;
      res.send({
        'access_token': access_token
      });
    }
  });
});

响应如下:

{
   "access_token": "NgCXRK...MzYjw",
   "token_type": "Bearer",
   "scope": "user-read-private user-read-email",
   "expires_in": 3600,
   "refresh_token": "NgAagA...Um_SHo"
}

TLDR:检查您的访问令牌是否已过期,如果已过期,请发送刷新令牌以接收新的访问令牌,然后可以再次用于获取数据。您还将收到一个新的刷新令牌以及来自该令牌的响应,该过程将重新开始。

甄越
2023-03-14

我设法让它工作的方式是通过下面的代码:

const express = require('express');
const SpotifyWebApi = require('spotify-web-api-node');

var generateRandomString = function(length) {
    var text = '';
    var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    for (var i = 0; i < length; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }

    return text;
};

var scopes = ['user-read-private', 'user-read-email', 'playlist-read-private', 'playlist-modify-private'],
    redirectUri = '<redirect uri>',
    clientId = '<client id>',
    clientSecret = '<client secret>',
    state = generateRandomString(16);

// Setting credentials can be done in the wrapper's constructor, or using the API object's setters.
var spotifyApi = new SpotifyWebApi({
    redirectUri: redirectUri,
    clientId: clientId,
    clientSecret: clientSecret
});

// Create the authorization URL
var authorizeURL = spotifyApi.createAuthorizeURL(scopes, state);

// https://accounts.spotify.com:443/authorize?client_id=5fe01282e44241328a84e7c5cc169165&response_type=code&redirect_uri=https://example.com/callback&scope=user-read-private%20user-read-email&state=some-state-of-my-choice
console.log(authorizeURL);

// --------------------------------

var credentials = {
    clientId: '<client id>',
    clientSecret: '<client secret>',
    redirectUri: '<redirect uri>'
};

var spotifyApi = new SpotifyWebApi(credentials);

var app = express();

app.get('/login', function(req, res) {
    res.redirect(authorizeURL);
});

// The code that's returned as a query parameter to the redirect URI
var code = '<authorization code>'; // this does not need to be updated

// Retrieve an access token and a refresh token
spotifyApi.authorizationCodeGrant(code).then(
    function(data) {
        console.log('The token expires in ' + data.body['expires_in']);
        console.log('The access token is ' + data.body['access_token']);
        console.log('The refresh token is ' + data.body['refresh_token']);

        // Set the access token on the API object to use it in later calls
        spotifyApi.setAccessToken(data.body['access_token']);
        spotifyApi.setRefreshToken(data.body['refresh_token']);
    },
    function(err) {
        console.log('Something went wrong!', err);
    }
);
// --------------------------------------------------
// clientId, clientSecret and refreshToken has been set on the api object previous to this call.
function refreshSpotifyToken() {
    spotifyApi.refreshAccessToken().then(
        function(data) {
            console.log('The access token has been refreshed!');

            // Save the access token so that it's used in future calls
            spotifyApi.setAccessToken(data.body['access_token']);
            console.log('The access token is ' + data.body['access_token']);
            console.log('The token expires in ' + data.body['expires_in']);
        },
        function(err) {
            console.log('Could not refresh access token', err);
        });
};
client.on('ready', () => {
    refreshSpotifyToken();
    setInterval(refreshSpotifyToken, 1000 * 59 * 59);
})
 类似资料:
  • 我不熟悉,它代表。我混淆了它的两个术语:访问令牌和刷新令牌。 用户注册/登录站点后,我创建和。 将刷新标记保存在数据库或cookie中。 15分钟后,用户标记访问令牌过期。 如果用户空闲2小时,我将从cookie或DB中删除刷新令牌,否则我将使用刷新令牌续订访问令牌。 有什么优化的方法可以达到这个目的吗?

  • 授权服务器可以给Web应用客户端和本机应用程序客户端颁发刷新令牌。 刷新令牌在传输和储存时必须保持机密性,并只与授权服务器和刷新令牌被颁发的客户端共享。授权服务器必须维护刷新令牌和它被颁发给的客户端之间的绑定。刷新令牌必须只能使用带有RFC2818定义的服务器身份验证的1.6所述的TLS 传输。 授权服务器必须验证刷新令牌和客户端身份之间的绑定,无论客户端身份是否能被验证。当无法进行客户端身份验证

  • 刷新令牌是用于获取访问令牌的凭据。刷新令牌由授权服务器颁发给客户端,用于在当前访问令牌失效或过期时,获取一个新的访问令牌,或者获得相等或更窄范围的额外的访问令牌(访问令牌可能具有比资源所有者所授权的更短的生命周期和更少的权限)。颁发刷新令牌是可选的,由授权服务器决定。如果授权服务器颁发刷新令牌,在颁发访问令牌时它被包含在内(即图1中的步骤D)。 刷新令牌是一个代表由资源所有者给客户端许可的授权的字

  • 我对oauth2中的刷新令牌有点困惑。如它所说的访问令牌限制了黑客可以使用用户凭证的1小时的时间窗口,刷新令牌是万岁令牌,可以用来重新创建访问令牌。 我很困惑,如果有人从cookie中窃取了访问令牌,他也可以窃取刷新令牌,并可以使用刷新令牌创建新的访问令牌,因为我在JQuery中有ajax请求(客户端)

  • 我在自己的Web API上使用Oauth2,在Web应用程序上使用ASP.NET C#来使用该API。在我的web应用程序上,我正在进行HttpWebRequests。当我的访问令牌过期时,我调用一个方法“refreshToken”,该方法发出请求以获取新的访问令牌。这工作很好,没有问题...除了我得到的响应包含一个新的刷新令牌???我在等新的访问令牌。我甚至认为在没有再次传递凭据的情况下这是不可

  • 我正在构建一个移动应用程序,并且正在使用JWT进行身份验证。 最好的方法似乎是将JWT访问令牌与刷新令牌配对,这样我就可以根据需要频繁地使访问令牌过期。 刷新令牌是什么样子的?是随机字符串吗?那串加密了吗?是另一个JWT吗? 刷新令牌将存储在用户模型的数据库中以便访问,对吗?在这种情况下似乎应该加密 在用户登录后,我是否会将刷新令牌发送回,然后让客户端访问单独的路由来检索访问令牌?