Announcements

Help Wizard

Step 1

NEXT STEP

FAQs

Please see below the most popular frequently asked questions.

Loading article...

Loading faqs...

VIEW ALL

Ongoing Issues

Please see below the current ongoing issues which are under investigation.

Loading issue...

Loading ongoing issues...

VIEW ALL

Spotify OAuth invalid authorization code

Spotify OAuth invalid authorization code

I am receiving a 400 code response from Spotify when attempting to exchange an auth code for an access token. The authorization code is correct and works with my application. My frontend sends the auth code to the backend which has a view method that performs the request. Even though I have checked at least ten times that the client secret, ID, etc. are all correct, I continuously receive an "Invalid authorization code" from the Spotify Web API. Here's my view method where I am 100% certain that the code the frontend provides is valid as it works on the frontend for requesting resources:


 

 

def exchange_code_for_tokens(request):
    authorization_code = request.data.get('code')

    if not authorization_code:
        return Response({'detail': 'Authorization code is required.'}, status=status.HTTP_400_BAD_REQUEST)

    data = {
        'grant_type': 'authorization_code',
        'code': authorization_code,
        'redirect_uri': 'http://localhost:3000/spotify-authentication-callback',
    }

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

    response = requests.post(SPOTIFY_TOKEN_URL, data=data, headers=headers)

    if response.status_code == 200:
        token_data = response.json()
        access_token = token_data.get('access_token')
        refresh_token = token_data.get('refresh_token')
        expires_in = token_data.get('expires_in')

        return Response({
            'access_token': access_token,
            'refresh_token': refresh_token,
            'expires_in': expires_in,
        })
    else:
        print(
            f"Error response from Spotify: {response.status_code}, {response.text}")
        return Response({'detail': response.json().get('error_description', 'Unable to exchange code for tokens.')}, status=response.status_code)


def get_encoded_credentials():
    credentials = f"{SPOTIFY_CLIENT_ID}:{SPOTIFY_CLIENT_SECRET}"
    encoded_credentials = base64.b64encode(
        credentials.encode('utf-8')).decode('utf-8')
    return encoded_credentials

 

 

Reply
0 Replies

Suggested posts