Search code examples
pythonpython-3.xoauthebay-apiauthlib

eBay and Authlib Unconventional token type


I'm trying to use Authlib library to access new eBay REST API (as Authorization code grant)

Here is my code;

import json
import os
import webbrowser
from time import time

from authlib.integrations.requests_client import OAuth2Session
from rpi_order_data_sync import settings


def auth(seller):
    def token_updater(token, seller=seller):
        if not os.path.exists(seller):
            open(seller, "w").close()
        with open(seller, "w") as token_file:
            json.dump(token, token_file)

    scope = ["https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly"]

    if not os.path.exists(seller):

        ebay = OAuth2Session(
            settings.E_APP_ID,
            settings.E_CERT_ID,
            redirect_uri=settings.E_RU_NAME,
            scope=scope,
        )

        uri, state = ebay.create_authorization_url(
            "https://auth.sandbox.ebay.com/oauth2/authorize",
        )

        print("Please go to {} and authorize access.".format(uri))

        try:
            webbrowser.open_new_tab(uri)
        except webbrowser.Error:
            pass

        authorization_response = input("Please enter callback URL: ")  # nosec

        token = ebay.fetch_token(
            "https://api.sandbox.ebay.com/identity/v1/oauth2/token",
            authorization_response=authorization_response,
        )

        print(token)

        token_updater(token)

        return ebay

The problem is eBay's token response has an unconventional token type named "User Access Token" instead of "Bearer". Therefore I get this error;

Traceback (most recent call last):
  File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/authlib/integrations/requests_client/oauth2_session.py", line 37, in __call__
    req.url, req.headers, req.body = self.prepare(
  File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/authlib/oauth2/auth.py", line 91, in prepare
    sign = self.SIGN_METHODS[token_type.lower()]
KeyError: 'user access token'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/bin/rods", line 11, in <module>
    load_entry_point('rpi-order-data-sync', 'console_scripts', 'rods')()
  File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/home/thiras/HDD/freelancer/contentassasin/rpi-order-data-sync/rpi_order_data_sync/main.py", line 132, in sync_ebay_orders
    orders = ebay.get(
  File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/requests/sessions.py", line 543, in get
    return self.request('GET', url, **kwargs)
  File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/authlib/integrations/requests_client/oauth2_session.py", line 113, in request
    return super(OAuth2Session, self).request(
  File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/requests/sessions.py", line 516, in request
    prep = self.prepare_request(req)
  File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/requests/sessions.py", line 449, in prepare_request
    p.prepare(
  File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/requests/models.py", line 318, in prepare
    self.prepare_auth(auth, url)
  File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/requests/models.py", line 549, in prepare_auth
    r = auth(self)
  File "/home/thiras/.local/share/virtualenvs/rpi-order-data-sync-tA0i1rrc/lib/python3.8/site-packages/authlib/integrations/requests_client/oauth2_session.py", line 41, in __call__
    raise UnsupportedTokenTypeError(description=description)
authlib.integrations.base_client.errors.UnsupportedTokenTypeError: unsupported_token_type: Unsupported token_type: 'user access token'

I've noticed Compliance fix for non-standard section at Authlib documentation but couldn't figure out how to do this fix or even possible in this way.


Solution

  • I've found a solution and it also works with requests-oauthlib package. It seems working flawlessly so far. The main struggle was to create a fake request.Response model since request.Response has no setter for .text or .content attributes so modifying them was impossible.

    So I've created a FakeResponse class that only mimics .json() method since it was the only method used by Authlib.

    class FakeResponse:
        """ Fake Class for Request Response class. """
    
        def __init__(self, data):
            self.data = data
    
        def json(self):
            """ Mocks requests.Response.json(). """
            return self.data
    

    After that I've created an access_token_response hook;

    def non_compliant_token_type(resp):
        data = resp.json()
        data["token_type"] = "Bearer"
        fake_resp = FakeResponse(data=data)
        return fake_resp
    

    Please let me know if you have a better answer or any recommendations to improve it.