如何从重定向中获取访问令牌 url

How to get access token from redirect url

我想从 Spotify 得到一个 access token。我从 Spotify 得到一些这样的:

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

我在地址栏中看到了它。 https://example.com/callback 是我的网站,access_token 需要价值。如何获得?

我这样试过,但是得到 None

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

完整代码

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) 

我通过服务 repl.it 做我的项目。也许这就是为什么我不能像这样读取请求的参数

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

解决方案

从 Spotify 重定向到 /callback_token。在这种情况下,函数 arg tokenNone。我的页面 callback_token.html 被解析 url 并使用 token.

重定向到 callback_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 与 javascript

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