okta / okta-sdk-python

Apache License 2.0
229 stars 143 forks source link

Access token expiry not handled when using OAuth 2.0 #363

Open lboynton opened 1 year ago

lboynton commented 1 year ago

When using OAuth 2.0 to authenticate with the Okta API, an access token is generated. This token is cached by the SDK and after some time expires, but there appears to be no logic in place to handle the token expiry and get a new access token.

There is a clear_access_token method to clear the access token, but I don't see where it's being used.

haggrip commented 11 months ago

We have also experienced issues relating to token expiry when authenticating with a private key. As a work around, we call the clear_access_token manually and clearing the request executor cache and headers to get a new token in the next request:

 def _clear_access_token():
    okta_client._request_executor._oauth.clear_access_token()
    okta_client._request_executor._cache.delete("OKTA_ACCESS_TOKEN")
    okta_client._request_executor._default_headers.pop("Authorization")

We would also like to know if there's a supported way of refreshing these tokens

lboynton commented 11 months ago

Thanks @haggrip! Tried something similar to this but I was missing the trick to clear the Authorization header, without that the old token is still used.

bryanapellanes-okta commented 10 months ago

@lboynton Thank you for submitting this. We will review further internally; see comment here: https://github.com/okta/okta-sdk-python/pull/364#issuecomment-1691725925

Internal Ref#: OKTA-641384

jccaldw1 commented 1 month ago

My team has struggled with this issue. The way we have remediated this is to examine the exp claim on the token, and if we determine the token is expired, simply clear the access token before the next request and force the Client to request a new OAuth token. But this can also be done preemptively when we first grab the access token from the OAuth object - I have taken the liberty to draft this pull request that implements this change.

Of course, happy to see that pull request closed if this is not the intended direction for the SDK. As @haggrip mentioned, perhaps an alternative future direction could be refreshing the token instead of simply clearing it and requesting a new token.