Spotify API authentication with Python

流过昼夜 提交于 2019-12-24 13:07:59

问题


I'm trying to authenticate a user in the Spotify API, but it keeps returning me the error code "invalid_client". I'm implementing that on a Python Django solution, that's my code:

headers = {'Authorization': 'Basic '+standard_b64encode(client_id)+standard_b64encode(client_secret)}
r = requests.post('https://accounts.spotify.com/api/token', {'code': code, 'redirect_uri': redirect_uri, 'grant_type': grant_type, 'headers': headers}).json()

Any idea why it's not working?


回答1:


In spotify api docs it is: Authorization Required. Base 64 encoded string that contains the client ID and client secret key. The field must have the format: Authorization: Basic base64 encoded( client_id:client_secret)

So i guess you should do:

import base64
'Authorization' : 'Basic ' + base64.standard_b64encode(client_id + ':' + client_secret)

It's working for me so try it. If it doesn't work my code is:

@staticmethod
def loginCallback(request_handler, code):
    url = 'https://accounts.spotify.com/api/token'
    authorization = base64.standard_b64encode(Spotify.client_id + ':' + Spotify.client_secret)

    headers = {
        'Authorization' : 'Basic ' + authorization
        } 
    data  = {
        'grant_type' : 'authorization_code',
        'code' : code,
        'redirect_uri' : Spotify.redirect_uri
        } 

    data_encoded = urllib.urlencode(data)
    req = urllib2.Request(url, data_encoded, headers)

    try:
        response = urllib2.urlopen(req, timeout=30).read()
        response_dict = json.loads(response)
        Spotify.saveLoginCallback(request_handler, response_dict)
        return
    except urllib2.HTTPError as e:
        return e

Hope it helps!




回答2:


Are you sure you're providing client_id & client_secret in the proper format? Looking at the docs, it suppose to be separated with :.

Also try to run the same flow with curl first and then replicate with python.



来源:https://stackoverflow.com/questions/27554994/spotify-api-authentication-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!