'How can I add context to authlib's update_token hook?
My Flask application is using authlib
to allow multiple users to connect multiple Google service accounts via OAuth. When those credentials are refreshed, I'd like to automatically save them using the update_token
hook. However, this function does not seem to have enough context to know which user, and which connection for that user, is being refreshed.
My code looks like this:
from flask import Flask
from authlib.integrations.flask_client import OAuth
app = Flask(__name__)
def update_token(token, refresh_token=None, access_token=None):
print("updating token")
# Question: How can I pass "user_id", "connection_id", or any other identifier?
db.update_token(user_id, connection_id, token)
oauth = OAuth(app)
oauth.register(
name="ga",
client_kwargs={
"scope": "https://www.googleapis.com/auth/analytics.readonly",
"prompt": "consent",
},
client_id="x",
client_secret="x",
server_metadata_url="x",
api_base_url="https://analyticsreporting.googleapis.com",
token_url="https://oauth2.googleapis.com/token",
update_token=update_token
)
@app.route('/<user_id>')
def user(user_id):
def internal_update_token(token, refresh_token=None, access_token=None):
# This is never called
print("This is my new update token function.")
# Doesn't work
# c = oauth_plugin.create_client("ga", update_token=None)
c = oauth_plugin.create_client("ga")
# Doesn't work either
c.update_token = internal_update_token
The code will correctly refresh the token and call update_token()
, however, with many users or many connections, I don't have a way to add context to that update_token function so that I can update the correct row in my database with the new credentials.
How can I accomplish this? In some cases, I might have multiple clients being used in the same request, working asynchronously. How can I know which token needs to be updated in my database?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|