I am trying to authenticate user authentication through spotipy in my flask backend, which was working by itself. But when I try to introduce the front end components, it seems like the backend isn't sending the correct information OR the frontend is getting the wrong information. I tried making sure that I was sending cookies correctly from my backend, and that my cache wasn't being used to memorize whether a user was or wasn't logged in. I am very new to Web dev, especially front end so any help would be greatly appreciated.
Here is what I am expecting to happen with my code
- Check for a cached token or user authentication state on load.
- Redirect the user to the Spotify login if not authenticated.
- Handle the callback from Spotify and check the authentication state.
- Redirect back to localhost:3000/ where my frontend is hosted so it can check again, this time supposedly showing that the user has been logged in.
Here is the relevant code on my backend:
@app.route('/')
def index():
cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
auth_manager = spotipy.oauth2.SpotifyOAuth(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=REDIRECT_URI, scope='user-read-currently-playing',
cache_handler=cache_handler)
if not auth_manager.validate_token(cache_handler.get_cached_token()):
auth_url = auth_manager.get_authorize_url()
#print(auth_url)
return jsonify({"logged_in": False, "auth_url": auth_url})
spotify = spotipy.Spotify(auth_manager=auth_manager)
user_info = spotify.me()
return jsonify({
"logged_in": True,
"user_info": {
"display_name": user_info["display_name"],
"id": user_info["id"],
"uri": user_info["uri"],
"profile_url": user_info["external_urls"]["spotify"]
}
})
@app.route('/callback')
def callback():
code = request.args.get('code')
print(code)
if code:
cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
auth_manager = spotipy.oauth2.SpotifyOAuth(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=REDIRECT_URI, scope='user-read-currently-playing',
cache_handler=cache_handler)
auth_manager.get_access_token(code)
session.modified = True
response = make_response(redirect('http://localhost:3000/'))
return response
return 'Missing code parameter. Please try again.', 400
And here is my App.js on the frontend:
function App() {
const [message, setMessage] = useState('');
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [authUrl, setAuthUrl] = useState('');
useEffect(() => {
const url = `http://127.0.0.1:5000/?t=${Date.now()}`;
axios.get(url, { withCredentials: true })
.then(response => {
const { logged_in, auth_url } = response.data;
console.log(response.data);
setIsLoggedIn(logged_in);
if (!logged_in) {
setAuthUrl(auth_url);
console.log('Redirecting to:', auth_url);
}
})
.catch(error => console.error('Error:', error));
}, []);
return (
<Router>
<div className="App">
<div className="App-header">
<Routes>
<Route path="/login" element={!isLoggedIn ? <Login authUrl={authUrl} /> : <Navigate to="/" />} /> // Use the Login component here
<Route path="/" element={isLoggedIn ? <SearchBar onSearch={setMessage} /> : <Navigate to="/login" />} />
</Routes>
</div>
</div>
</Router>
);
}
export default App;
I did some testing, and in the callback function, if I redirect just back to localhost:5000, it will show me this data:
"logged_in": True,
"user_info": { etc etc...
Which is what I want the front end to detect. But for some reason it still picks up logged_in as false.
When utilizing
spotipyfor the authorization code flow, you don't necessarily need to handle the callback endpoint with redirection yourself.Spotipysupports several authentication flows provided by Spotify, including the Authorization Code Flow.When
Spotipyis described as middleware for the Authorization Code Flow, it means thatSpotipycan handle much of the authentication process seamlessly within your Python application.Spotipy is middleware. So you don't necessary to handle
./callbackendpoint.Demo
Back-end server by
FlaskAPI Testing by Postman
Clear Session
Get Logged In
Login
Note- This API will only call by React
Front-end Code
App.js
Result of Front-end
References
How to enable CORS in flask
Session Example in Flask
flask-cookie-decode
How to get client_id, client_secret and redirect_uri and user id
Current playlist with Spotipy
Step 1
Step 1 result