How to make requests from another flask route using the flask oauth2 client in authlib

177 Views Asked by At

I am using the oauth2 flask client in the authlib library. Following the documentation I am able to run the oauth.my_server.authorize_access_token() method inside the /authorize route, which sets the oauth.my_server.token to the token value.

But I am now having problems making a get request to the remote server from another route. I can see that after redirecting from the /authorize route, the token attribute becomes None.

from flask import url_for, render_template

@auth.route('/login')
def login():
    redirect_uri = url_for('authorize', _external=True)
    return oauth.my_server.authorize_redirect(redirect_uri)

@auth.route('/authorize')
def authorize():
    token = oauth.my_server.authorize_access_token()
    print(token == oauth.my_server.token)  # <-- True
    return redirect(url_for('other.some_other_route'))

So on return we get the token and store it in the oauth client object, but then the token is gone after redirecting to the next route:

@other.route('/some_other_route', methods=['GET'])
def some_other_route():
    print("Token after redirect: ", oauth.my_server.token)  # <-- None
    oauth.my_server.get('resource')  # Gives error
    return ""

The error given when trying oauth.my_server.get('resource') is: authlib.integrations.base_client.errors.MissingTokenError: missing_token. I think this is expected behaviour, but I can't see an example in the docs for how to make requests from another route. Should I store it in the session object (or a cache?) and then just reassign it manually with oauth.my_server.token = session.get('token')?

0

There are 0 best solutions below