Making Spotify OAuth requests with Flask without redirect

I have a Flask app that handles Spotify authentication using the authorization code flow. The current setup works fine, but I want to change how it works. Right now my code redirects users to Spotify’s auth page, but I want to make a GET request instead and then handle the callback.

from flask import Flask, request, jsonify, redirect
import requests
import base64
import urllib.parse

app = Flask(__name__)
app.secret_key = 'my_secret_key'

AUTH_ENDPOINT = 'https://accounts.spotify.com/authorize'
TOKEN_ENDPOINT = 'https://accounts.spotify.com/api/token'
API_URL = 'https://api.spotify.com/v1'

APP_ID = 'your_client_id'
APP_SECRET = 'your_client_secret'
CALLBACK_URL = 'http://localhost:5000/auth_callback'

@app.route('/')
def index():
    return "Welcome <a href='/auth'>Connect Spotify</a>"

@app.route('/auth')
def authenticate():
    permissions = 'user-read-private user-read-email'
    query_params = {
        'client_id': APP_ID,
        'response_type': 'code', 
        'redirect_uri': CALLBACK_URL,
        'scope': permissions,
        'show_dialog': True
    }
    
    spotify_auth_url = f"{AUTH_ENDPOINT}?{urllib.parse.urlencode(query_params)}"
    return redirect(spotify_auth_url)

@app.route('/auth_callback')
def handle_callback():
    if 'error' in request.args:
        return jsonify({'error': request.args['error']})
    
    auth_code = request.args.get('code')
    if not auth_code:
        return jsonify({'error': 'Missing authorization code'})
    
    # Encode credentials
    credentials = base64.b64encode(
        f"{APP_ID}:{APP_SECRET}".encode()
    ).decode()
    
    request_headers = {
        'Authorization': f'Basic {credentials}',
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    
    token_data = {
        'grant_type': 'authorization_code',
        'code': auth_code,
        'redirect_uri': CALLBACK_URL
    }
    
    try:
        token_response = requests.post(TOKEN_ENDPOINT, headers=request_headers, data=token_data)
        token_response.raise_for_status()
        return jsonify(token_response.json())
    except requests.exceptions.RequestException as error:
        return jsonify({
            'error': 'Token request failed',
            'message': str(error)
        }), 500

if __name__ == '__main__':
    app.run(port=5000, debug=True)

The problem is when I try to make a GET request instead of redirecting to the auth URL, I can receive the callback parameters but I get authorization errors when trying to POST for the access token. Is this something Spotify designed on purpose to prevent this approach? I’m using the authorization code flow correctly but wondering if there’s a way around the redirect requirement.

yeah, the redirect is key for security. spotify checks for the referrer and user agent to prevent CSRF. you can’t just bypass it with a GET. users must log in on spotify’s page. if permissions aren’t critical, you might wanna look into the client credentials flow.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.