首页 > 解决方案 > Spotify API 授权代码流失败({'error': 'invalid_grant', 'error_description': 'Invalid authentication code'})

问题描述

因此,我正在尝试从头开始构建 Spotify API 授权代码流,并且我有以下代码:

class SpotifyAPIFlow(object):
    access_token = None
    access_token_expires = datetime.datetime.now()
    access_token_did_expire = True
    client_id = None
    client_secret = None
    token_url = "https://accounts.spotify.com/api/token"
    auth_url = "https://accounts.spotify.com/authorize"

    def __init__(self, client_id, client_secret, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.client_id = client_id
        self.client_secret = client_secret

    def get_client_credentials(self):
        """
        :return: a base 64 encoded string
        """
        client_id = self.client_id
        client_secret = self.client_secret
        if client_secret is None or client_id is None:
            raise Exception("You must set client id and client secret!\n")
        client_creds = f"{client_id}:{client_secret}"
        client_creds_b64 = base64.b64encode(client_creds.encode())
        return client_creds_b64.decode()

    def get_token_headers(self):
        client_creds_b64 = self.get_client_credentials()
        return {"Authorization": f"Basic {client_creds_b64}"}

    def get_token_data(self):
        return {"grant_type": "authorization_code"}

   def perform_authentication(self):
        auth_url = self.auth_url
        headers = {'client_id': self.client_id, 'response_type': 'code',
                   'redirect_uri': 'https://open.spotify.com/collection/playlists', 'scope': 'user-top-read'}
        auth_code = requests.get(auth_url, headers)
        print(auth_code.headers['set-cookie'])


        token_headers = self.get_token_headers()

        payload = {
            'grant_type': 'authorization_code',
            'code': auth_code,
            'redirect_uri': 'https://open.spotify.com/collection/playlists',
        }
        #
        access_token_request = requests.post(url=self.token_url, data=payload, headers=token_headers)
        access_token_response_data = access_token_request.json()
        print(access_token_response_data)
        # access_token = access_token_response_data['access_token']

对于 perform_authentication 函数中的第一个请求,我收到状态为 200 的响应,据我所知,这意味着一切都很好,但我发现真正粗略的是,在请求后它没有重定向我全部到任何网站,无论出于何种原因,他们甚至没有让我接受范围(我正在使用 pycharm),我知道身份验证代码应该与它重定向到的 url 相关,但它没有将我重定向到任何东西
因为我仍然是这个东西的初学者,我很感激任何关于为什么它不能按我想要的那样工作的帮助,谢谢。

标签: pythonauthenticationrequestspotify

解决方案


推荐阅读