Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spotify API {'error': 'invalid_client'} Authorization Code Flow [400]

This is one of my many attempts at making a POST request to https://accounts.spotify.com/api/token.

Scope was set to 'playlist-modify-public, playlist-modify-private'.

I'm using Python 3.7, Django 2.1.3.

No matter what I do, response_data returns {'error': 'invalid_client'}

I've tried many things, including passing the client_id/client_secret inside the body of the request as per the official Spotify documentation for this particular request... to no avail.

Please help!

def callback(request):

    auth_token = request.GET.get('code')     # from the URL after user has clicked accept
    code_payload = {
        'grant_type': 'authorization_code',
        'code': str(auth_token),
        'redirect_uri': REDIRECT_URI,
    }

    auth_str = '{}:{}'.format(CLIENT_ID, CLIENT_SECRET)
    b64_auth_str = base64.b64encode(auth_str.encode()).decode()

    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Basic {}'.format(b64_auth_str)
    }

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

    response_data = json.loads(post_request.text)
        # ==> {'error': 'invalid_client'}
like image 318
Charlotte Prevost Avatar asked Dec 01 '18 04:12

Charlotte Prevost


Video Answer


3 Answers

I suspect the issue is with invalid characters in your Authorization header. Try using urlsafe_b64encode instead of b64encode to prepare that header value:

b64_auth_str = base64.urlsafe_b64encode(auth_str.encode()).decode()
like image 96
solarissmoke Avatar answered Oct 17 '22 09:10

solarissmoke


From the documentation

An alternative way to send the client id and secret is as request parameters (client_id and client_secret) in the POST body, instead of sending them base64-encoded in the header.

    SPOTIFY_TOKEN = "https://accounts.spotify.com/api/token"
    request_body = {
        "grant_type": GRANT_TYPE,
        "code": code,
        "redirect_uri": REDIRECT_URI,
        "client_id": SPOTIFY_CLIENT_ID,
        "client_secret": SPOTIFY_CLIENT_SECRET,
    }
    r = requests.post(url=SPOTIFY_TOKEN, data=request_body)
    resp = r.json()

This works as well.

like image 8
Harshit Singhai Avatar answered Oct 17 '22 11:10

Harshit Singhai


Here is another problem mentioned. If the error is

INVALID_CLIENT: Invalid redirect URI

then you need to register your URI. Quote from the source - to have everything at one place:

Simply log in, find your app and click "Edit Settings" in the top right section. Under redirect URIs you add REDIRECT_URI and remember to click save in the bottom. This should resolve your issue.

like image 1
Michał Zaborowski Avatar answered Oct 17 '22 09:10

Michał Zaborowski