简体   繁体   中英

Spotify API callback to Vue frontend gives error on Flask backend

I'm working on a small website using a Flask backend (running on localhost:5000), Vue frontend (running on localhost:8080) and various 3rd party APIs, most notably Spotify . I use the spotipy package and a Flask backend to fetch the data from Spotify. As per the Spotify user authorization and the spotipy implementation , I need to provide a callback URI for Spotify.

Here's the auth process I have:

oauth = SpotifyOAuth(client_id=environ.get("SPOTIFY_CLIENT_ID"), client_secret=environ.get("SPOTIFY_CLIENT_SECRET"),
                     redirect_uri="http://localhost:8100/callback", scope=scopes)
sp = spotipy.Spotify(auth_manager=oauth)

The above has a global scope, and authorization occurs when I make a call to the Spotify API through spotipy eg in this endpoint and its helper method

@app.route('/currently-playing', methods=['GET'])
def now_playing():
   return get_currently_playing()

def get_currently_playing():
    '''
        Gets the user's currently playing track
    '''
    return jsonify(sp.current_user_playing_track())

which I call on the frontend like this:

async fetchCurrentlyPlaying() {
     let response = await axios.get(`http://localhost:5000/currently-playing`);

However, the redirect_uri matches the callback URI I have listed for the app on my Spotify developer account. However, the callback URI matches neither the Flask backend nor the the Vue frontend. And, I'm not running anything on localhost:8100. When I first hit Spotify's API and it takes me to the 'Do you grant the following permissions to this app' page and I accept, I am then redirected to a new tab at http://localhost:8100/callback?code={code_here} and get this response:

Spotify 回调响应

The 'Close Window' button does nothing and I'm forced to reload the frontend (localhost:8080), but then all works. What I'd like is for the callback URI to be on the Vue frontend , eg localhost:8080/callback, so I can display a similar message and the redirect the user back to the home page, but if I change the callback on developer.spotify.com and the spotipy auth to this

oauth = SpotifyOAuth(client_id=environ.get("SPOTIFY_CLIENT_ID"), client_secret=environ.get("SPOTIFY_CLIENT_SECRET"),
                     redirect_uri="http://localhost:8080/callback", scope=scopes)

sp = spotipy.Spotify(auth_manager=oauth)

, then even though I have defined that route on the Vue router

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
  },
  {
    path: "/callback",
    name: "Callback",
    component: Callback,
  },

I get the following error on my Flask backend:

File "C:\Python39\Lib\site-packages\flask\app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Python39\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Python39\Lib\site-packages\flask_cors\extension.py", line 165, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "C:\Python39\Lib\site-packages\flask\app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python39\Lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Python39\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Python39\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Python39\Lib\site-packages\flask_cors\extension.py", line 165, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "C:\Python39\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python39\Lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Python39\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Python39\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\kriel\spotify-flask\server\app.py", line 94, in now_playing
    return get_currently_playing()
  File "C:\Users\kriel\spotify-flask\server\spotipy_helper.py", line 165, in get_currently_playing
    return jsonify(sp.current_user_playing_track())
  File "C:\Python39\Lib\site-packages\spotipy\client.py", line 1169, in current_user_playing_track
    return self._get("me/player/currently-playing")
  File "C:\Python39\Lib\site-packages\spotipy\client.py", line 291, in _get
    return self._internal_call("GET", url, payload, kwargs)
  File "C:\Python39\Lib\site-packages\spotipy\client.py", line 221, in _internal_call
    headers = self._auth_headers()
  File "C:\Python39\Lib\site-packages\spotipy\client.py", line 212, in _auth_headers
    token = self.auth_manager.get_access_token(as_dict=False)
  File "C:\Python39\Lib\site-packages\spotipy\oauth2.py", line 484, in get_access_token
    "code": code or self.get_auth_response(),
  File "C:\Python39\Lib\site-packages\spotipy\oauth2.py", line 439, in get_auth_response
    return self._get_auth_response_local_server(redirect_port)
  File "C:\Python39\Lib\site-packages\spotipy\oauth2.py", line 405, in _get_auth_response_local_server
    server = start_local_http_server(redirect_port)
  File "C:\Python39\Lib\site-packages\spotipy\oauth2.py", line 1227, in start_local_http_server
    server = HTTPServer(("127.0.0.1", port), handler)
  File "C:\Python39\Lib\socketserver.py", line 452, in __init__
    self.server_bind()
  File "C:\Python39\Lib\http\server.py", line 138, in server_bind
    socketserver.TCPServer.server_bind(self)
  File "C:\Python39\Lib\socketserver.py", line 466, in server_bind
    self.socket.bind(self.server_address)
OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions

even though I have this to enable CORS on the Flask backend [and don't get CORS errors otherwise]

# enable CORS
CORS(app, resources={r'/*': {'origins': '*'}})

I get this error even if I change the callbacks to localhost:5000/callback (ie to Flask).

How do I get around this? It's clunky and not a great user experience.

Many thanks in advance!

According to the Spotipy documentation :

The redirect_uri argument or SPOTIPY_REDIRECT_URI environment variable must match the redirect URI added to your application in your Dashboard

Did you change the default redirect URI in your Spotify developer dashboard ? This could be the cause of those socket errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM