Making GET requests to Spotify authorization without redirect in Flask

I have a Flask application connecting to Spotify’s API using the authorization code flow. The process runs smoothly when I redirect users to the authorization URL with the necessary parameters.

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

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

SPOTIFY_AUTH_ENDPOINT = 'https://accounts.spotify.com/authorize'
SPOTIFY_TOKEN_ENDPOINT = 'https://accounts.spotify.com/api/token'
APP_ID = 'your_client_id'
APP_SECRET = 'your_client_secret'
CALLBACK_URL = 'http://localhost:5000/auth_callback'

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

@app.route('/authenticate')
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"{SPOTIFY_AUTH_ENDPOINT}?{urllib.parse.urlencode(query_params)}"
    return redirect(spotify_auth_url)

@app.route('/auth_callback')
def auth_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': 'Authorization code missing'})
    
    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(SPOTIFY_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)

My issue is that I want to skip the redirect and make a direct GET request for authorization. However, when I attempt this, I can’t seem to obtain the necessary authorization for the POST request to retrieve the access token. Is this something Spotify has intentionally restricted? I’m curious to know if there’s a workaround or if the redirect is essential for the authorization code flow to function correctly.

nah you cant skip the redirect, thats the whole point of oauth2 authorization code flow. spotify needs the user to manually consent on their auth page - theres no way around it. if you want programatic access without user interaction, look into client credentials flow instead but that has limited scopes.

The redirect is actually mandatory for security reasons in OAuth2’s authorization code flow. What you’re trying to do would essentially bypass the user consent mechanism that Spotify requires. The authorization endpoint returns an HTML page with a consent form, not JSON data you can parse programmatically. I’ve worked with similar implementations and found that the redirect serves as a security boundary - it ensures the user actually sees and approves the permissions your app is requesting. Even if you could somehow extract the authorization code from the HTML response, you’d still need to handle the user interaction part. For server-to-server scenarios where you don’t need user-specific data, the client credentials flow works well. But if you need user permissions, you’re stuck with the authorization code flow and its redirect requirement. Some developers implement a headless browser approach for automation, but that violates Spotify’s terms of service.