简体   繁体   English

Spotify api 返回无效的刷新令牌,即使刷新令牌是新的

[英]Spotify api returning invalid refresh token even though the refresh token is new

I'm trying to get new access token from spotify by sending the refresh token to spotify token endpoints but it's returning this {error: 'invalid_grant', error_description: 'Invalid refresh token'}我正在尝试通过将刷新令牌发送到 Spotify 令牌端点来从 Spotify 获取新的访问令牌,但它返回此 {error: 'invalid_grant', error_description: 'Invalid refresh token'}

this is my code:这是我的代码:

const basic = Buffer.from(
         `${import.meta.env.VITE_CLIENT_ID}:${import.meta.env.VITE_CLIENT_SECRET}`
      ).toString("base64");
      const params = new URLSearchParams();
      params.append("grant_type", "refresh_token");
      params.append("refresh_token", import.meta.env.VITE_REFRESH_TOKEN);

      const response = await fetch("https://accounts.spotify.com/api/token", {
         method: "POST",
         headers: {
            Authorization: `Basic ${basic}`,
            "Content-Type": "application/x-www-form-urlencoded"
         },
         body: params.toString()
      });

      const result = await response.json();
      return result;

It's suppose to return a new access token but it's returning error for some reasons i don't understand.它应该返回一个新的访问令牌,但由于某些我不明白的原因它返回错误。

Note: I got the access token and refresh token from this website https://alecchen.dev/spotify-refresh-token/ after inputting my client id and client secret.注意:在输入我的客户端 ID 和客户端密码后,我从这个网站https://alecchen.dev/spotify-refresh-token/获得了访问令牌和刷新令牌。 If i use the access token directly to make a request to spotify api it works but i need to refresh it to get a new one but it's returning error如果我直接使用访问令牌来请求 spotify api 它有效但我需要刷新它以获得新的但它返回错误

You needs to call this format in body of POST.您需要在 POST 的正文中调用此格式。

grant_type = refresh_token
refresh_token = <received refresh_token>
access_token= <received access_token>

在此处输入图像描述

The website https://alecchen.dev/spotify-refresh-token/ has a potential leak your credential.网站https://alecchen.dev/spotify-refresh-token/可能leak您的凭据。

I will shows getting refresh token in local and update refresh token.我将展示在本地获取刷新令牌和更新刷新令牌。

Demo Code.演示代码。

Save as get-token.js file.另存为get-token.js文件。

const express = require("express")
const axios = require('axios')
const cors = require("cors");

const app = express()
app.use(cors())

CLIENT_ID = "<your client id>"
CLIENT_SECRET = "<your client secret>"
REDIRECT_URI = '<your redirect URI>' // my case is 'http://localhost:3000/callback'
SCOPE = [
    "user-read-email",
    "playlist-read-collaborative"
]

app.get("/login", (request, response) => {
    const redirect_url = `https://accounts.spotify.com/authorize?response_type=code&client_id=${CLIENT_ID}&scope=${SCOPE}&state=123456&redirect_uri=${REDIRECT_URI}&prompt=consent`
    response.redirect(redirect_url);
})

app.get("/callback", async (request, response) => {
    const code = request.query["code"]
    await axios.post(
        url = 'https://accounts.spotify.com/api/token',
        data = new URLSearchParams({
            'grant_type': 'authorization_code',
            'redirect_uri': REDIRECT_URI,
            'code': code
        }),
        config = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            params: {
                'grant_type': 'client_credentials'
            },
            auth: {
                username: CLIENT_ID,
                password: CLIENT_SECRET
            }
        })
        .then(resp1 => {
            axios.post(
                url = 'https://accounts.spotify.com/api/token',
                data = new URLSearchParams({
                    'grant_type': 'refresh_token',
                    'refresh_token': resp1.data.refresh_token,
                    'access_token': resp1.data.access_token
                }),
                config = {
                    auth: {
                        username: CLIENT_ID,
                        password: CLIENT_SECRET
                    }
                }
            ).then(resp2 => {
                return response.send(JSON.stringify([resp1.data, resp2.data]));
            })
        });

})
// your port of REDIRECT_URI
app.listen(3000, () => {
    console.log("Listening on :3000")

Install dependencies安装依赖

npm install express axios cors

Run a local server and access it运行本地服务器并访问它

node get-token.js

Open your browser and enter this address打开你的浏览器并输入这个地址

http://localhost:3000/login

It will get code and both tokens then exchange the exchanged token .它将获得codeboth tokens ,然后交换exchanged token

It Will display both tokens and exchanged token in Browser.它将在浏览器中显示令牌和交换的令牌。

Result结果

First red box is get access-token and refresh-token第一个红框是get access-tokenrefresh-token

Second red box is to grant the refresh-token第二个红色框是授予refresh-token

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM