Announcements

Help Wizard

Step 1

NEXT STEP

Invalid Authorization Code - Authorization Code Flow

Invalid Authorization Code - Authorization Code Flow

Plan

Premium

Country

US

Device

PC

Operating System

Windows 10

 

My Question or Issue

I'm trying to request an access token using the /token endpoint with python requests library but keep receiving this error: {'error': 'invalid_grant', 'error_description': 'Invalid authorization code'}. Here's a snippet of my code:

 

 

 

 

import os
import base64
import requests

client_id = os.environ.get('CLIENT_ID')
client_secret = os.environ.get('CLIENT_SECRET')

# taking spotify application variables and base64 encoding
credentials = client_id + ':' + client_secret
credentials_bytes = credentials.encode('utf-8')
credentials_encoded = base64.b64encode(credentials_bytes)
authorization = credentials_encoded.decode('utf-8')

def token_request(code,redirect_uri):
    headers = {
        "Content-Type":"application/x-www-form-urlencoded",
        "Authorization": f'Basic {authorization}'
        }
    body = {
        "grant_type":"authorization_code",
        "code":code,
        "redirect_uri":f'{redirect_uri}'
        }

    response = requests.post(
    'https://accounts.spotify.com/api/token',
    data=body,
    headers=headers
    )

    token = response.json()
    return token

 

 

 

 

I'm not sure what issue might to give me this error because I sent the same data through cURL and received an expected response.

Example cURL:

 

 

 

 

curl -H "Authorization: Basic *<base64 encoded client_id:client_secret>*" -d grant_type=authorization_code -d code=code_from_user_authorization -d redirect_uri=http://my_redirect_uri https://accounts.spotify.com/api/token

 

 

 

 

Reply
0 Replies

Suggested posts