Search code examples
pythonflaskoauth-2.0authlibrequests-oauthlib

Obtaining and storing refresh token using Authlib with flask


I'm using the authlib https://github.com/lepture/authlib obtain user authentication to their data, so a daily offline scheduler can download some data on the behalf of the user.

I first register the client:

google = oauth.register(
    'google',
    client_id = '***',
    client_secret = '***',
    access_token_url = "https://www.googleapis.com/oauth2/v4/token", 
    access_token_params = None,
    authorize_url = "https://accounts.google.com/o/oauth2/v2/auth",
    authorize_params = None,
    api_base_url = 'https://googleapis.com/oauth2/v1/',
    client_kwargs={'scope': 'https://www.googleapis.com/auth/doubleclickbidmanager'}
)

and at a later stage I retrieve the token using:

token = oauth.google.authorize_access_token()

when I print the token, I see that Google has not return the refresh token that I need to store on my database for offline use:

{'access_token': '***', 'expires_in': 3599, 'scope': 'https://www.googleapis.com/auth/doubleclickbidmanager', 'token_type': 'Bearer', 'expires_at': 1591750317}

Can I change the way I register the client with access_type = offline in order to let Google know that I need the refresh token too? How do I get and store the refresh token?


Solution

  • Here is the solution for adding access_type to authorization endpoint:

    google = oauth.register(
        'google',
        # ...
        authorize_params={'access_type': 'offline'},
    )
    

    Use this authorize_params to pass extra parameters to authorize_url.