How to refresh access_token via refresh_token?
AlexNik opened this issue ยท 9 comments
Is it implemented?
https://www.nic.ru/help/oauth-server_5809.html Refreshing access token
section
Need to implement a method in DnsApi class that will wrap refresh_token from requests_oauthlib.
@AlexNik Implemented, please try checking out branch https://github.com/andr1an/nic-api/tree/feature/refresh-token-support
I will try to test it tommorow.
Could you add return token to these places
Hmm, will think about it. For now I look on those methods more like on procedures that just modify the state (they are setting self._token
) and not return anything. You can either use token_updater_clb
or access api._token
in your script.
token_updater_clb
is pretty easy to use โ you need to pass a method that will call i.e. json.dump()
on its argument:
import json
import os
from oauthlib.oauth2.rfc6749.tokens import OAuth2Token
TOKEN_CACHE_FILE = os.path.join(os.path.expanduser("~"), ".nic_ru_token.json")
def _load_token():
with open(TOKEN_CACHE_FILE, "r") as fp_token:
token_data = json.load(fp_token)
return OAuth2Token(token_data)
def _save_token(token):
with open(TOKEN_CACHE_FILE, "w") as fp_token:
json.dump(token, fp_token)
def test_add_delete_commit():
token = _load_token()
api = DnsApi(
app_login="xxxxxx",
app_password="xxxxxx",
token=token,
token_updater_clb=_save_token,
)
api.default_service = "DP12345678"
api.default_zone = "nicapitest.ru"
rec_1 = ARecord("1.1.1.1", name="foobar")
added = api.add_record(rec_1)
api.delete_record(added[0].id)
api.commit()
I see.
The access_token
is refreshed by OAuth2Session
automatically, yes?
Not sure if it works properly, but the code is written for the support of automatic refresh https://github.com/andr1an/nic-api/blob/feature/refresh-token-support/nic_api/__init__.py#L216-L221
OAuth2Session
should check if self._token["expires_at"]
is too close to the current time on each GET/POST/PUT/DELETE. If token is about to expire and refresh_token
is present, the session should request a new token. You can test it with api.logger.setLevel(logging.DEBUG)
โ you will see all requests that the code does.
Could you release new version to PyPi?