3

This question relates to authlib python module:

I'm using an authlib OAuth2Session to trigger a lot of requests to an API. I provided a refresh_token_url to my OAuth2Session, so that the access_token is seamlessly refreshed when expired.

Most of the time, it works perfectly, but sometimes, I receive a 401 response (token expired). What I suspect is : the request is fired on the client side since the token is not expired yet, but it becomes expired by the time this request is processed on the server side...

Here is my question: Is there a way to make OAuth2Session refresh its token x seconds before it expires? Would it be possible to add an integer attribute to OAuth2Session to make this duration configurable?

Géraud
  • 1,923
  • 3
  • 20
  • 20

1 Answers1

3

There is a general best practice as an OAuth client - if you want the most reliable experience:

  • Call an API
  • If you get a 401 get a new token and retry the API call
  • If you still get an error display it to the user

Note that a 401 can occur even if an access token is not expired - eg 5 minute clock differences between client and server - or token signing certificate changed

Here is some example code in case it helps. If you are lucky authlib does this for you - if not it is well worth coding it yourself ..

Gary Archer
  • 22,534
  • 2
  • 12
  • 24