mercredi 2 novembre 2016

Handling OAuth 2 Refresh Tokens

One of the applications I am developing is going to need to access a service on behalf of the the client authenticated with OAuth 2.0.

OAuth 2.0 gives you both a access and refresh tokens for your client (resource owner). You then will make requests and at some point the token will expire and will need to be refreshed (possibly half way through multiple requests to the service).

I wanted to get some thoughts on how other people have handled this as it's new to me and there may be a much simpler way of dealing with OAuth's refresh tokens.

This is the way I'm currently thinking about approaching it. This basically sudo code at this point to get the idea across - it most certainly wont run :). The idea is to write a wrapper and decorate all oauth authenticated calls that, on failure, will try to refresh the token and retry.

from functools import wraps

def oauth_expirable(f):
    @wraps(f)
    def wrapper(*args, refresh_token, **kwds):
        try:
            return f(*args, refresh_token=refresh_token, **kwds)
        except HTTPError as http_error:
            if http_error.code == 403:
                http.post('http://ift.tt/2eofHj8', body={'refresh_token': refresh_token})
                return f(*args, refresh_token=refresh_token, **kwds)
            else:
                raise
    return wrapper

@oauth_expirable
def get_resource(uid, *, auth_token, refresh_token):
    return http.get(
        url='http://ift.tt/2fio6C0{}'.format(uid), 
        headers={'Authentication': 'Bearer: {}'.format(auth_token)})

Any thoughts on this solution or on alternative solutions.

Thanks

Aucun commentaire:

Enregistrer un commentaire