Python authlib flask如何显式授权_重定向?

2024-06-01 00:18:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有“代码授予流”登录,authlib flask集成运行良好:

redirect_uri = url_for('authorize', _external=True)
return oauth.myOauth2.authorize_redirect(redirect_uri)

出于某种原因,我决定尝试使重定向更加可见。向用户显示一下我的应用程序,然后再重定向到一些人可能不太熟悉的登录页面

现在这种作品:

redirect_uri = url_for('authorize', _external=True)
aurl = oauth.myOauth2.create_authorization_url(redirect_uri)
# what to do with aurl['state']?
return render_template('redirect.html', delay=2,
                       redirect_notice='Redirecting to login', 
                       redirect_url=aurl['url'])

然而,当我在登录后被重定向回“authorize”时,我得到了authlib.integrations.base_client.errors.MismatchingStateError: mismatching_state: CSRF Warning! State not equal in request and response.,我认为这是因为我没有保存aurl['state']

但我怎么能做到呢?我很难弄清楚授权重定向是如何做到的。
也许有更好的办法?感谢您的帮助


Tags: totrueurlforreturnurioauth重定向
1条回答
网友
1楼 · 发布于 2024-06-01 00:18:35

有两种方法可以完成工作:

  1. .authorize_redirect提取url:
redirect_uri = url_for('authorize', _external=True)
resp = oauth.myOauth2.authorize_redirect(redirect_uri)
url = resp.headers.get('Location')
return render_template('redirect.html', delay=2,
                       redirect_notice='Redirecting to login', 
                       redirect_url=url)
  1. 使用.save_authorize_data保存CSRF和其他数据:
redirect_uri = url_for('authorize', _external=True)
rv = oauth.myOauth2.create_authorization_url(redirect_uri)
oauth.myOauth2.save_authorize_data(request, redirect_uri=redirect_uri, **rv)
return render_template('redirect.html', delay=2,
                       redirect_notice='Redirecting to login', 
                       redirect_url=rv['url'])

你可以从:https://github.com/lepture/authlib/blob/master/authlib/integrations/flask_client/remote_app.py#L51学习

相关问题 更多 >