Hello so I have a frontend written in react with a FastAPI (python) backend, I am trying to authenticate against Spotify User account (Auth Code flow).
This was literally working a few days ago but I somehow messed something up, I can no longer get my frontend to open the Spotify Auth dialog by setting my browser window to the following url:
The user should be shown the Auth dialog to authorize my app to use their account data, and AFTER it should redirect to localhost/callback
where my frontend sends the corresponding auth code to my backend for token exchange (the Backend for Frontend auth pattern).
I checked the docs and they confirm:
After the user accepts, or denies your request, the Spotify OAuth 2.0 service redirects the user back to your redirect_uri.
Instead, the user is instantly redirected to localhost
without authorizing, and the followup token exchange on the backend fails for "invalid (auth) code".
Here is my typescript code to manually set the browser window to that URL address:
const state = generateRandomString(STATE_LENGTH);
localStorage.setItem(STATE_KEY, state);
const params = {
response_type: "code",
client_id: CLIENT_ID,
scope: SCOPE,
redirect_uri: REDIRECT_URI,
state: state,
};
// "https://accounts.spotify.com/authorize"
const spotifyUserAuthUrl = new URL(OAUTH_AUTHORIZE_URL);
spotifyUserAuthUrl.search = new URLSearchParams(params).toString();
// Don't use navigate() from react router, since it is not designed for external navigation
window.location.href = spotifyUserAuthUrl.toString();
This is called when the user clicks a button to open the normal Spotify Auth dialog, but as I said above, it now just instantly redirects to my REDIRECT_URI, which is http://localhost:3000/callback
.
Checking the ‘network’ tab in browser tools, I see that this spotifyUserAuthUrl
is hit by a GET
request with a 302 response, and the response headers contain my redirect URL.
So why am I suddenly making a GET
request to the Spotify OAuth auth URL, which I believe is instantly triggering the redirect (which happens to contain an invalid Auth code, presumably because the Spotify auth dialog never shows up so the user can’t authorize)? My code clearly tells the browser to navigate to that URL, it never makes a GET
request.
Thanks so much for your help!
2
Answers
I realized it was simply because Spotify saves the user's login info after the initial login, so you have to manually sign yourself out from https://accounts.spotify.com/en/logout to proc the Auth dialog to open.
I am currently looking for a way to programmatically sign the user out, and I will probably start with the suggestions here.
You can force the spotify authorize dialog by including
show_dialog: true
in your request URL params, even if the user is already signed in.For example:
'https://accounts.spotify.com/authorize?response_type=code&show_dialog=true&'
… etcAs seen in the spotify docs: