question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Possible to auto refresh client_credentials access token?

See original GitHub issue

As a client_credentials based access token has no refresh token, the refresh_token() functionality raises an exception (ie. InvalidRequestError: Missing refresh token parameter.). Based on the spec, I believe this is technically fine - one should fetch a new access token in this case.

Is it just the spec that prevents requests-oauthlib from handling this scenario gracefully alongside the current token expiration code handling in the request() method on OAuth2Session?

If I subclass OAuth2Session like so:

class RefreshOAuth2Session(OAuth2Session):
    def request(self, *args, **kwargs):
        try:
            return super().request(*args, **kwargs)
        except TokenExpiredError:
            self.token = self.fetch_token(
                token_url=OAUTH2_TOKEN_URL,
                **self.auto_refresh_kwargs
            )
            self.token_updater(self.token)
            return super().request(*args, **kwargs)

I can use it like this:

class MyClass(object):
    _session = None
    _token = None

    def token_updater(self, token):
        self._token = token

    @property
    def session(self):
        if self._session is None:
            self._session = RefreshOAuth2Session(
                client=BackendApplicationClient(client_id=self.client_id),
                token=self.token,
                token_updater=self.token_updater,
                auto_refresh_kwargs={
                    'client_id': self.client_id,
                    'client_secret': self.client_secret,
                }
            )
        return self._session

    @property
    def token(self):
        if self._token is None:
            self._token = RefreshOAuth2Session(
                client=BackendApplicationClient(client_id=self.client_id)
            ).fetch_token(
                token_url=OAUTH2_TOKEN_URL,
                client_id=self.client_id,
                client_secret=self.client_secret
            )
        return self._token

    def __init__(self, *args, **kwargs):
        super(MyClass, self).__init__(*args, **kwargs)
        self.client_id = CLIENT_ID
        self.client_secret = CLIENT_SECRET

    def get_information(self):
        return self.session.get('https://localhost:10000/api/infomation/')


obj = MyClass()
obj.get_information()

As long as auto_refresh_url is not passed in, the logic in my subclass handles everything smoothly. Could logic be added to request() to cover this scenario, rather than having to kludge this as I’ve done?

Related thread: https://groups.google.com/d/msg/django-oauth-toolkit/iSIiZQtn0mM/5SDckbyTCQAJ

Issue Analytics

  • State:open
  • Created 7 years ago
  • Reactions:2
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
IvanAnishchukcommented, Mar 17, 2017

I solved this issue by subclassing oauthlib’s BackendApplicationClient and adding

    def prepare_refresh_body(self, body='', refresh_token=None, scope=None, **kwargs):
        return self.prepare_request_body(boby=body, scope=scope, **kwargs)

Then you can pass such a client to Oauth2Session as normal.

But, indeed, a solution that doesn’t require custom code would be most welcome.

0reactions
singingwolfboycommented, Jan 9, 2020

Is anyone working on a solution to this?

Unfortunately, probably not. See #385 for more context.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to Automatically Request and Refresh OAuth2 Client ...
The response from the authorization server includes an access token which then must be passed on the request to Order Service in order...
Read more >
What Are Refresh Tokens and How to Use Them Securely
This post will explore the concept of refresh tokens as defined by OAuth 2.0. We will learn how they compare to other token...
Read more >
Refresh Tokens - OAuth 2.0 Simplified
The presence of the refresh token means that the access token will expire and you'll be able to get a new one without...
Read more >
Refreshing an Access Token for Client Credentials Flow
I was wondering what the best way is for me to refresh an access token that is obtained through the client credentials ......
Read more >
OAuth 2.0 Refresh Token Best Practices - Fusebit
The authorization server automatically issues a new access token once it expires. Depending on your application's needs - both options are valid ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found