Python authlib flask - how to do authorize_redirect explicitly?

隐身守侯 提交于 2021-01-29 08:21:06

问题


I have "code grant flow" login with the authlib flask integration working nicely:

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

For some reason I decided I want to try to make the redirect a bit more visible. Show users my app for a moment before redirecting to a login page that may be more unfamiliar for some.

Now this kind of works:

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'])

However, when I'm redirected back to "authorize" after login, I get authlib.integrations.base_client.errors.MismatchingStateError: mismatching_state: CSRF Warning! State not equal in request and response. which I presume is because I did not save aurl['state'].

But how can I actually do that? I'm having a hard time teasing out how authorize_redirect does it.
Maybe there is a better way altogether? Any help appreciated!


回答1:


There are two ways to get your job done:

  1. extract url from .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)
  1. use .save_authorize_data to save CSRF and other data:
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'])

You can learn it from: https://github.com/lepture/authlib/blob/master/authlib/integrations/flask_client/remote_app.py#L51



来源:https://stackoverflow.com/questions/64528686/python-authlib-flask-how-to-do-authorize-redirect-explicitly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!