使用Spotify API进行OAuth 2.0身份验证期间出现KeyError:"access_token" [英] KeyError: 'access_token' during OAuth 2.0 authentication using Spotify API

查看:86
本文介绍了使用Spotify API进行OAuth 2.0身份验证期间出现KeyError:"access_token"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个简单的应用程序来学习Python 3和Flask.目标是使用Spotify API中的数据,为此,我需要使用OAuth 2.0进行身份验证.

I'm building a simple application to learn Python 3 and Flask. The goal is to consume data from the Spotify API and for that I need to authenticate using OAuth 2.0.

我可以向Spotify帐户提供凭据,但是在回调过程中发生了以下错误:

I'm able to provide my credentials to Spotify Accounts however during the callback the following error is happening:

File "app.py", line 59, in callback
    access_token = response_data["access_token"]
KeyError: 'access_token'

代码示例:

post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload, headers=headers)

response_data = json.loads(post_request.text)
access_token = response_data["access_token"]
token_type = response_data["token_type"]
expires_in = response_data["expires_in"]
refresh_token = response_data["refresh_token"]

这是 API文档中的请求响应示例:

This is the request response sample from the API documentation:

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

我很迷路.不确定是与API响应内容有关,还是与JSON.loads(post_request.text)进行关联的应用程序如何解析.

I'm quite lost. Not sure if it's something related to the API response content or how the application is parsing it with json.loads(post_request.text).

编辑:获取HTTP状态代码后,我对问题有了一个初步的认识:

EDIT: After getting the HTTP status code I'm able to have an idea of the problem:

requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://accounts.spotify.com/api/token

但是我仍然无法弄清楚我的请求出了什么问题:

However I still can't figure it out what is wrong with my request:

authentication_token = request.args['code']
code_payload = {
    "grant_type": "authorization_code",
    "code": str(authentication_token),
    "redirect_uri": REDIRECT_URI
}
encoded_oauth2_tokens = base64.b64encode('{}:{}'.format(CLIENT_ID, CLIENT_SECRET).encode())
headers = {"Authorization": "Basic {}".format(encoded_oauth2_tokens)}
post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload, headers=headers)
post_request.raise_for_status()

推荐答案

您确定您确实从Spotify Web API获取数据而不是错误响应吗?

Are you sure you actually getting data from Spotify Web API and not error response?

这是我使用的并且效果很好

This is what I use and it works well

@dataclass
class Tokens:
    access: str
    refresh: str
    expires_at: int

# Class that sets up authorization_headers
# Class method
def get_tokens(self, code_from_redirect_uri: str) -> bool:
        payload: dict = {'redirect_uri': self._redirect_uri, 'code': code_from_redirect_uri,
                        'grant_type': 'authorization_code', 'scope': self._scope}
        response: Response = post(OAUTH_TOKEN_URL, data=payload, headers=self.authorization_headers)
        # When we don't get the OK response - we assume code was bad
        if response.status_code != 200:
            return False

        token_info: dict = response.json()
        self.tokens = Tokens(token_info['access_token'], token_info['refresh_token'], token_info['expires_in']*1000 + time())
        return True

这篇关于使用Spotify API进行OAuth 2.0身份验证期间出现KeyError:"access_token"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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