lepture / authlib

The ultimate Python library in building OAuth, OpenID Connect clients and servers. JWS,JWE,JWK,JWA,JWT included.
https://authlib.org/
BSD 3-Clause "New" or "Revised" License
4.39k stars 436 forks source link

Allow to disable expired token auto-refresh #632

Open roman-kachanovsky opened 4 months ago

roman-kachanovsky commented 4 months ago

Is your feature request related to a problem? Please describe.

My data supplier uses HTTP headers to route requests, so I have to add suitable headers to fetch_token and get methods to reach correct API endpoint:

session = OAuth2Session(client, secret, scope=['read', 'search'])
session.fetch_token(api_url, headers=auth_headers)  # same url, different headers
session.get(api_url, headers=data_headers)

And previously I handled token expiration by try..except block and get new token "manually":

try:
    r = session.get(api_url, headers=data_headers)
    if r.status_code == 401:
        session.fetch_token(api_url, headers=auth_headers)
        return session.get(api_url, headers=data_headers)
    return r
except (InvalidTokenError, MissingTokenError):
    session.fetch_token(api_url, headers=auth_headers)
    return session.get(api_url, headers=data_headers)

But now the approach throws "Invalid URL 'None': No scheme supplied. Perhaps you meant https://None?". As I understand, it's because ensure_active_token method sees "client_credentials" grant type and tries to update the token automatically via "token_endpoint", which is not set.

In my case I can't just add token_endpoint=api_url to OAuth2Session initialization, because the endpoint also requires suitable headers. At the same time ensure_active_token method always calls fetch_token with default headers.

Describe the solution you'd like

I would like to see any of 3 possible solutions: