I’m developing a music application that uses a React frontend and a Flask backend with Spotify’s OAuth authentication. It successfully authenticates when I run only my Flask server. However, once I incorporate it with my React application, I encounter issues regarding the session data.
The process should follow these steps:
- The frontend checks if the user is logged in.
- If not logged in, it redirects to the Spotify authentication page.
- After logging in on Spotify, the app should handle the callback and save the authentication token.
- The app should then redirect back to the React application, where the user is expected to be authenticated.
Here are the routes for my Flask backend:
@app.route('/auth-status')
def auth_status():
session_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
auth_manager = spotipy.oauth2.SpotifyOAuth(
client_id=SPOTIFY_CLIENT_ID,
client_secret=SPOTIFY_CLIENT_SECRET,
redirect_uri=CALLBACK_URL,
scope='user-read-playback-state',
cache_handler=session_handler
)
if not auth_manager.validate_token(session_handler.get_cached_token()):
login_url = auth_manager.get_authorize_url()
return jsonify({"authenticated": False, "login_url": login_url})
spotify_client = spotipy.Spotify(auth_manager=auth_manager)
user_profile = spotify_client.me()
return jsonify({
"authenticated": True,
"profile": {
"name": user_profile["display_name"],
"user_id": user_profile["id"],
"spotify_uri": user_profile["uri"],
"external_url": user_profile["external_urls"]["spotify"]
}
})
@app.route('/spotify-redirect')
def spotify_redirect():
auth_code = request.args.get('code')
if auth_code:
session_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
auth_manager = spotipy.oauth2.SpotifyOAuth(
client_id=SPOTIFY_CLIENT_ID,
client_secret=SPOTIFY_SECRET,
redirect_uri=CALLBACK_URL,
scope='user-read-playback-state',
cache_handler=session_handler
)
auth_manager.get_access_token(auth_code)
session.modified = True
return redirect('http://localhost:3000/')
return 'Missing authorization code', 400
Below is the React component handling this:
function MainComponent() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [loginUrl, setLoginUrl] = useState('');
useEffect(() => {
const checkAuthUrl = `http://127.0.0.1:5000/auth-status?timestamp=${Date.now()}`;
axios.get(checkAuthUrl, { withCredentials: true })
.then(response => {
const { authenticated, login_url } = response.data;
setIsLoggedIn(authenticated);
if (!authenticated) {
setLoginUrl(login_url);
}
})
.catch(error => console.error('Failed request:', error));
}, []);
return (
<BrowserRouter>
<div className="MainComponent">
<header className="app-header">
<Routes>
<Route path="/login" element={!isLoggedIn ? <LoginPage loginUrl={loginUrl} /> : <Navigate to="/" />} />
<Route path="/" element={isLoggedIn ? <SearchMusic /> : <Navigate to="/login" />} />
</Routes>
</header>
</div>
</BrowserRouter>
);
}
I’ve verified that when I call the Flask endpoint directly after the callback, it responds with authenticated: True along with user information. However, my React application continues to receive authenticated: false. What might be causing the session persistence issue between the frontend and the backend?