I'm starting with Authlib for a client credentials flow in an application I'm working on. The client only needs to:
- Authenticate with a service for write access to a protected resource using client credentials
- Submit a
POST
request to the protected resource.
However, I find that I'm having to do a lot of manual stepping through the authentication flow including:
fetch_token
- Store the resulting token
- On each
POST
request check if the token is expired - If expired, call
refresh_token
- Revoke the current token on session close
I thought all of this was done automatically by using a authlib.integrations.requests_client.OAuth2Session
so I feel like I'm doing something wrong.
In my most basic attempts where I thought the flow was automatic here's what I had:
if self._session is None:
self._session = OAuth2Session(
client_id=self._config.auth.client_id,
client_secret=self._config.auth.client_secret.get_secret_value(),
token_endpoint=self._config.auth.token_url,
)
response = self._session.post(
url=full_url,
headers={"Content-Type": "application/json"},
json=model.to_json(),
)
response.raise_for_status()
The result of this is a MissingTokenError
being raised. I tried passing withhold_token=True
as well, which prevents the MissingTokenError
but instead ends up with requests.exceptions.HTTPError: 401 Client Error: UNAUTHORIZED
.
All of this indicates to me that authentication isn't actually happening automatically, which is how I ended up doing so much manually.
What am I doing wrong here? Any help is appreciated!