I’m having a weird issue with my Spotify integration. When I first test my app, everything works fine - I can log in with one Spotify account and get the right access token. But here’s the problem: when I restart my application and try logging in with a completely different Spotify account (even using incognito mode to avoid any cached data), the API keeps giving me the exact same access token as the previous user.
This doesn’t make sense to me because each user should get their own unique token. Has anyone experienced this before?
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from flask import Flask, request, url_for, session, redirect
import time
from secrets import token_hex
# Flask app setup
app = Flask(__name__)
app.secret_key = token_hex(32)
app.config['SESSION_COOKIE_NAME'] = 'spotify_session'
TOKEN_DATA = "access_token_data"
@app.route('/auth')
def authenticate():
spotify_auth = setup_spotify_oauth()
authorization_url = spotify_auth.get_authorize_url()
return redirect(authorization_url)
@app.route('/callback')
def callback_handler():
spotify_auth = setup_spotify_oauth()
session.clear()
auth_code = request.args.get('code')
access_data = spotify_auth.get_access_token(auth_code)
session[TOKEN_DATA] = access_data
return redirect(url_for('user_dashboard', _external=True))
def setup_spotify_oauth():
return SpotifyOAuth(
client_id = 'YOUR_CLIENT_ID_HERE',
client_secret = 'YOUR_CLIENT_SECRET_HERE',
redirect_uri=url_for('callback_handler', _external=True),
scope='user-read-private user-read-email playlist-read-private user-top-read user-read-recently-played',
)
def retrieve_token():
access_data = session.get(TOKEN_DATA, None)
if not access_data:
return None
current_time = int(time.time())
token_expired = access_data['expires_at'] - current_time < 60
if token_expired:
spotify_auth = setup_spotify_oauth()
access_data = spotify_auth.refresh_access_token(access_data['refresh_token'])
return access_data
if __name__ == '__main__':
app.run(debug=True)