AnsweredAssumed Answered

Using the refresh token in Python

Question asked by Brian Bennett on May 17, 2019
Latest reply on May 17, 2019 by Brian Bennett

I'm having trouble using the refresh token in a Python script to get a new access token for a user after the hour expires. I'm using the `requests_oauthlib` library to handle token calls.


I'm able to get the initial token and store it for a user along with the refresh token. Has anyone done this and, if so, would you be willing to share a working code sample?


Here's my Flask route:


from requests_oauthlib import OAuth2Session

def index():
    # check that the user exists. If so, log in.
    if not current_user.is_anonymous:

        # Update the session if a refresh is needed
        def token_updater(token):
            session['oauth_token'] = token
            current_user.token = session['oauth_token']

        # Check the user's refresh token
        if current_user.expiration < time.time():

            extra = {
                'grant_type': 'refresh_token'

            token = OAuth2Session(app.config['OAUTH_CREDENTIALS']['canvas']['id'],

            return redirect(url_for('dashboard'))

        # Start the OAuth2 login flow if the user does not exist.
        # This part works fine.
        return render_template('login.html')