pythonflaskauthlib

Python authlib flask - how to do authorize_redirect explicitly?


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!


Solution

  • 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