问题描述
我具有“代码授予流”登录名,并且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'])
但是,当我登录后重定向回“授权”时,我会得到authlib.integrations.base_client.errors.MismatchingStateError: mismatching_state: CSRF Warning! State not equal in request and response.
,这是因为我没有保存aurl['state']
。
但是我该怎么做呢?我很难弄清楚authorize_redirect的操作方式。
也许总有更好的方法?任何帮助表示赞赏!
解决方法
有两种方法可以完成工作:
- 从
.authorize_redirect
中提取网址:
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)
- 使用
.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',redirect_url=rv['url'])
您可以从https://github.com/lepture/authlib/blob/master/authlib/integrations/flask_client/remote_app.py#L51
中学习