Search code examples
pythonflaskoauthspotify

How to get access token from redirect url


I want to get a access token from Spotify. I get from Spotify some this:

https://example.com/callback#access_token=NwAExz...BV3O2Tk&token_type=Bearer&expires_in=3600&state=123

I see it into address bar. Where https://example.com/callback is my site and access_token needed value. How to get it?

I tried like this, but get None

print(flask.request.args.get('access_token'))

Full code

import flask 
app = flask.Flask(__name__)

@app.route("/")
def render_index():
    return flask.render_template('index.html')

@app.route("/redirect_spotify_token", methods = ['POST'])
def redirect_spotify_token():
    return flask.redirect('https://accounts.spotify.com/authorize?...')

@app.route("/callback/spotify_token", methods = ['POST', 'GET'])
def callback_token():
  #
  # how to get access token?
  #
  return 'ok'

if __name__ == "__main__":
  app.run(host='0.0.0.0', port=8080) 

Solution

  • I do my project via a service repl.it. Maybe that's why I can't read request's args like this

    flask.request.args.get('access_token')
    

    Solution

    Redirect from Spotify to /callback_token. In this case, function an arg token is None. The my page callback_token.html is parse url and redirect to callback_token() with token.

    main.py

    @app.route("/callback_token")
    @app.route("/callback_token/<token>")
    def callback_token(token=None):
        if token is None:
          return render_template('callback_token.html')
        else:
          #logic with token
          return redirect(url_for('index'))
    

    callback_token.html with javascript

    var parsedHash = new URLSearchParams(
        window.location.hash.substr(1)
    );
    location.href = `your_url.com/callback_token/${parsedHash.get('access_token')}`