Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot request new token with auth code for the Digi-key API #556

Open
lpdx opened this issue Jan 25, 2024 · 10 comments
Open

Cannot request new token with auth code for the Digi-key API #556

lpdx opened this issue Jan 25, 2024 · 10 comments

Comments

@lpdx
Copy link

lpdx commented Jan 25, 2024

Issue / Problem report

  1. Add the KiCost version. Type kicost --version at terminal.

KiCost v1.1.18
kicost-digikey-api-v3 v0.1.3
Python 3.9.16 (KiCAD 7.0)
OS Windows 10 Enterprise, Zscaler running

The tool works well with the Mouser and Nexar API and the problem occurs when enabling Digi-Key API.

To isolate the problem, I created a fresh virtual env with Python 3.9.16 (same version as in KiCAD 7.0 installation) and installed just the kicost-digikey-api-v3.

Steps to reproduce:

  • Create a new python env conda create -n fresh python=3.9.16 and activate it
  • download, install and configure the kicost-digikey-api-v3 following the procedure here
  • enter the downloaded kicost-digikey-api-v3 folder and run the test with python test_production.py
  • I had an error about SSL: CERTIFICATE_VERIFY_FAILED so I install python -m pip install pip-system-certs to solve
  • run python test_production.py again
  • the browser opens and asks to allow access, click "Allow" with the two options marked ("OAUTH.APPROVAL.PAGE.TEMPLATE.DEFAULTSCOPEDESCRIPTION" and "DEFINES WHAT USERS CAN VIEW ABOUT THEIR OWN PROFILE")
  • The page is updated for the callback url https://localhost:8139/digikey_callback?code=XXXX&scope=
  • Next page shows that "You may now close this window, Auth code retreived: XXXX"
  • After closing the page the log in the prompt shows this messages:
(fresh-env) C:\Users\username\git\kicost-digikey-api-v3>python test_production.py
2024-01-25 17:19:01,445 - kicost_digikey_api_v -    DEBUG: Digi-Key API plug-in options:
2024-01-25 17:19:01,445 - kicost_digikey_api_v -    DEBUG: ['DIGIKEY_STORAGE_PATH=C:\\Users\\username\\.cache\\kicost\\Digi-Key', 'DIGIKEY_CLIENT_ID=XXXXXXXXNc84M', 'DIGIKEY_CLIENT_SECRET=XXXXXXXX7Ks3f', 'DIGIKEY_CLIENT_SANDBOX=True']
2024-01-25 17:19:01,445 - kicost_digikey_api_v -    DEBUG: {}
Looking in cache C:\Users\username\.cache\kicost\Digi-Key\dpn_296-6501-6-ND_US_en_USD_US.dat
2024-01-25 17:19:01,445 - kicost_digikey_api_v -    DEBUG: Using API V3
2024-01-25 17:19:01,445 - kicost_digikey_api_v -  WARNING: Oauth2 token storage does not exist or malformed, creating new.
2024-01-25 17:19:01,445 - kicost_digikey_api_v -    DEBUG: AUTH - Authenticating with endpoint https://sandbox-api.digikey.com/v1/oauth2/authorize using ID: XXXXXXXX...
2024-01-25 17:19:01,445 - kicost_digikey_api_v -    DEBUG: AUTH - Redirect URL: https://localhost:8139/digikey_callback
2024-01-25 17:19:10,599 - kicost_digikey_api_v -    DEBUG: TOKEN - Exchanging F0XXQeIo auth code for token at endpoint: https://sandbox-api.digikey.com/v1/oauth2/token
2024-01-25 17:19:10,599 - kicost_digikey_api_v -    DEBUG: TOKEN - Using client id: XXXXXXXX...
2024-01-25 17:19:10,599 - kicost_digikey_api_v -    DEBUG: TOKEN - Using client secret: XXXXXXXX...
Traceback (most recent call last):
  File "C:\Users\username\git\kicost-digikey-api-v3\kicost_digikey_api_v3\oauth\oauth2.py", line 194, in __exchange_for_token
    r.raise_for_status()
  File "C:\Users\username\.conda\envs\fresh-env\lib\site-packages\requests\models.py", line 1021, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://sandbox-api.digikey.com/v1/oauth2/token

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\username\git\kicost-digikey-api-v3\test_production.py", line 29, in <module>
    part = o.search()
  File "C:\Users\username\git\kicost-digikey-api-v3\kicost_digikey_api_v3\utils.py", line 147, in search
    result = kicost_digikey_api_v3.product_details(self.dk_pn, api_limits=self.api_limit, includes=includes, **DK_API.extra_ops)
  File "C:\Users\username\git\kicost-digikey-api-v3\kicost_digikey_api_v3\v3\api.py", line 107, in product_details
    client = DigikeyApiWrapper('product_details_with_http_info', kicost_digikey_api_v3.v3.productinformation)
  File "C:\Users\username\git\kicost-digikey-api-v3\kicost_digikey_api_v3\v3\api.py", line 50, in __init__
    self._digikeyApiToken = kicost_digikey_api_v3.oauth.oauth2.TokenHandler(version=3, sandbox=self.sandbox).get_access_token()
  File "C:\Users\username\git\kicost-digikey-api-v3\kicost_digikey_api_v3\oauth\oauth2.py", line 301, in get_access_token
    token_json = self.__exchange_for_token(httpd.auth_code)
  File "C:\Users\username\git\kicost-digikey-api-v3\kicost_digikey_api_v3\oauth\oauth2.py", line 196, in __exchange_for_token
    raise DigikeyOauthException('TOKEN - Cannot request new token with auth code: {}'.format(e))
kicost_digikey_api_v3.exceptions.DigikeyOauthException: TOKEN - Cannot request new token with auth code: 403 Client Error: Forbidden for url: https://sandbox-api.digikey.com/v1/oauth2/token

PS.:
Before clicking in the "Allow" buttom this two certificate files are saved in the ~./.cache/kicost/Digi-Key folder.
image

And after the error occurs the certificate files in the ~./.cache/kicost/Digi-Key folder are gone.

The file config.txt:

DIGIKEY_CLIENT_ID=XXXXXXXXXXXXXXXXc84M
DIGIKEY_CLIENT_SECRET=XXXXXXKs3f
DIGIKEY_CLIENT_SANDBOX=True
@set-soft
Copy link
Collaborator

Disable the sandbox

@lpdx
Copy link
Author

lpdx commented Jan 26, 2024

Thank you for your return.

But even disabling the sandbox in the config.txt I'm getting the same error.

Here is the config.txt:

DIGIKEY_CLIENT_ID=CLIENT_ID_XXXcmM8k
DIGIKEY_CLIENT_SECRET=CLIENT_SECRET_XXXL6CPB
DIGIKEY_CLIENT_SANDBOX=False

And the log while running python test_production.py, after closing the webpage "You may now close this window, Auth code retreived: XXXX", this error occurs:

(fresh) C:\Users\username\git\kicost-digikey-api-v3>python --version
Python 3.9.16

(fresh) C:\Users\username\git\kicost-digikey-api-v3>python test_production.py
2024-01-26 09:17:48,074 - kicost_digikey_api_v -    DEBUG: Digi-Key API plug-in options:
2024-01-26 09:17:48,074 - kicost_digikey_api_v -    DEBUG: ['DIGIKEY_STORAGE_PATH=C:\\Users\\username\\.cache\\kicost\\Digi-Key', 'DIGIKEY_CLIENT_ID=CLIENT_ID_XXXcmM8k', 'DIGIKEY_CLIENT_SECRET=CLIENT_SECRET_XXXL6CPB', 'DIGIKEY_CLIENT_SANDBOX=False']
2024-01-26 09:17:48,074 - kicost_digikey_api_v -    DEBUG: {}
Looking in cache C:\Users\username\.cache\kicost\Digi-Key\dpn_296-6501-6-ND_US_en_USD_US.dat
2024-01-26 09:17:48,074 - kicost_digikey_api_v -    DEBUG: Using API V3
2024-01-26 09:17:48,074 - kicost_digikey_api_v -  WARNING: Oauth2 token storage does not exist or malformed, creating new.
2024-01-26 09:17:48,074 - kicost_digikey_api_v -    DEBUG: AUTH - Authenticating with endpoint https://api.digikey.com/v1/oauth2/authorize using ID: CLIENT_ID_XXX...
2024-01-26 09:17:48,074 - kicost_digikey_api_v -    DEBUG: AUTH - Redirect URL: https://localhost:8139/digikey_callback
2024-01-26 09:17:54,109 - kicost_digikey_api_v -    DEBUG: TOKEN - Exchanging A6hTUdtQ auth code for token at endpoint: https://api.digikey.com/v1/oauth2/token
2024-01-26 09:17:54,109 - kicost_digikey_api_v -    DEBUG: TOKEN - Using client id: CLIENT_ID_XXX...
2024-01-26 09:17:54,110 - kicost_digikey_api_v -    DEBUG: TOKEN - Using client secret: CLIENT_SECRET_XXX...
Traceback (most recent call last):
  File "C:\Users\username\git\kicost-digikey-api-v3\kicost_digikey_api_v3\oauth\oauth2.py", line 194, in __exchange_for_token
    r.raise_for_status()
  File "C:\Users\username\.conda\envs\fresh\lib\site-packages\requests\models.py", line 1021, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://api.digikey.com/v1/oauth2/token

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\username\git\kicost-digikey-api-v3\test_production.py", line 29, in <module>
    part = o.search()
  File "C:\Users\username\git\kicost-digikey-api-v3\kicost_digikey_api_v3\utils.py", line 147, in search
    result = kicost_digikey_api_v3.product_details(self.dk_pn, api_limits=self.api_limit, includes=includes, **DK_API.extra_ops)
  File "C:\Users\username\git\kicost-digikey-api-v3\kicost_digikey_api_v3\v3\api.py", line 107, in product_details
    client = DigikeyApiWrapper('product_details_with_http_info', kicost_digikey_api_v3.v3.productinformation)
  File "C:\Users\username\git\kicost-digikey-api-v3\kicost_digikey_api_v3\v3\api.py", line 50, in __init__
    self._digikeyApiToken = kicost_digikey_api_v3.oauth.oauth2.TokenHandler(version=3, sandbox=self.sandbox).get_access_token()
  File "C:\Users\username\git\kicost-digikey-api-v3\kicost_digikey_api_v3\oauth\oauth2.py", line 301, in get_access_token
    token_json = self.__exchange_for_token(httpd.auth_code)
  File "C:\Users\username\git\kicost-digikey-api-v3\kicost_digikey_api_v3\oauth\oauth2.py", line 196, in __exchange_for_token
    raise DigikeyOauthException('TOKEN - Cannot request new token with auth code: {}'.format(e))
kicost_digikey_api_v3.exceptions.DigikeyOauthException: TOKEN - Cannot request new token with auth code: 403 Client Error: Forbidden for url: https://api.digikey.com/v1/oauth2/token

From the Digi-key side looks like everything is ok:
image

@uzytkownik
Copy link

uzytkownik commented Jul 27, 2024

I run into the same problem. It looks like with GUI the DigiKey is configured twice - once with sandbox from setting and second time with sandbox disabled.

It works from commandline but breaks with GUI.

This is stacktrace of second configure:

  File "/nix/store/czz49vfk5cq2pdcssfkjbqnlb0hg7bh1-python3.11-kicost-1.1.19/bin/.kicost-wrapped", line 9, in <module>
    sys.exit(main())
             ^^^^^^
  File "/nix/store/czz49vfk5cq2pdcssfkjbqnlb0hg7bh1-python3.11-kicost-1.1.19/lib/python3.11/site-packages/kicost/__main__.py", line 479, in main
    main_real()
  File "/nix/store/czz49vfk5cq2pdcssfkjbqnlb0hg7bh1-python3.11-kicost-1.1.19/lib/python3.11/site-packages/kicost/__main__.py", line 410, in main_real
    kicost_gui(args.force_en_us, None, configure_kicost_apis, command_line_api_options, args)  # Use the user gui if no input is given.
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/nix/store/czz49vfk5cq2pdcssfkjbqnlb0hg7bh1-python3.11-kicost-1.1.19/lib/python3.11/site-packages/kicost/kicost_gui.py", line 1191, in kicost_gui
    configure_kicost_apis(args.config, args.config is None, command_line_api_options, args)
  File "/nix/store/czz49vfk5cq2pdcssfkjbqnlb0hg7bh1-python3.11-kicost-1.1.19/lib/python3.11/site-packages/kicost/__main__.py", line 171, in configure_kicost_apis
    configure_apis(api_options)
  File "/nix/store/czz49vfk5cq2pdcssfkjbqnlb0hg7bh1-python3.11-kicost-1.1.19/lib/python3.11/site-packages/kicost/distributors/__init__.py", line 90, in configure_apis
    distributor_class.configure_apis(options)
  File "/nix/store/czz49vfk5cq2pdcssfkjbqnlb0hg7bh1-python3.11-kicost-1.1.19/lib/python3.11/site-packages/kicost/distributors/distributor.py", line 244, in configure_apis
    api.configure(ops)
  File "/nix/store/czz49vfk5cq2pdcssfkjbqnlb0hg7bh1-python3.11-kicost-1.1.19/lib/python3.11/site-packages/kicost/distributors/api_digikey.py", line 105, in configure
    raise Exception
Exception

(Line 105 is the one I added)

I think somewhere string "False" is interpreted as True though I'm too lazy ATM to figure out where.

@set-soft
Copy link
Collaborator

set-soft commented Aug 6, 2024

It looks like with GUI the DigiKey is configured twice

Hi @uzytkownik ! I can't reproduce it. Can you send the traceback for the first configuration call?

In my system the API is configured just once.

@clwe
Copy link

clwe commented Sep 21, 2024

I have a similar (the same?) issue: kicost would only query the sandbox api, even if sandbox env variable is set False. When commenting out the respective lines to get the environment variables in api.py it works for me:
https://github.com/set-soft/kicost-digikey-api-v3/blob/575cd906354a0af685545ef20655f5f24ed5673b/kicost_digikey_api_v3/v3/api.py#L39C1-L44C17
I'm on MacOS Sonoma 14.5 and I installed kicost via pipx. Maybe this is OS specific?

Btw: If I register a sandbox API on digikey and give those credentials in the config.yaml, it successfully calls the sandbox API with the original code.

@set-soft
Copy link
Collaborator

Hi @clwe !
Did you try setting sandbox to false in the configuration file?

@clwe
Copy link

clwe commented Sep 24, 2024

yes, it even said sandbox=False in debug output

@set-soft
Copy link
Collaborator

yes, it even said sandbox=False in debug output

Double check your configuration file says sandbox: false (lowercase) in the Digi-Key section.
The printed value might be changed before its use.

@clwe
Copy link

clwe commented Oct 18, 2024

Sorry for the delay. I had False written upper case in the Digikey section of config.yaml. I changed the line to sandbox: false. But I still get the authorization error:

ERROR:Exception when calling manufacturer_product_details_with_http_info: (401)
Reason: Unauthorized
HTTP response headers: HTTPHeaderDict({'Date': 'Fri, 18 Oct 2024 16:25:47 GMT', 'Content-Type': 'application/json', 'Content-Length': '228', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '', 'Access-Control-Allow-Headers': 'origin, x-requested-with, accept, content-type, authorization,x-digikey-client-id, x-digikey-locale-site, x-digikey-locale-language, x-digikey-locale-currency, x-digikey-locale-shiptocountry, x-digikey-customer-id', 'Access-Control-Max-Age': '3628800', 'Access-Control-Allow-Methods': 'GET, POST', 'X-DIGIKEY-REQUEST-ID': '6c3c9f5e-2fee-424c-98b4-3a4f13115164', 'Set-Cookie': 'TS012a951d=01460246b69e3d88145da96ca5b902901ffd1b1c47ff7be3afa419e3207ab2362b00d1bb6659ef071d20b3258e8c78a78ea0953cca; Path=/; Secure; HTTPOnly'})
HTTP response body: {"ErrorResponseVersion":"3.0.0.0","StatusCode": 401,"ErrorMessage":"Invalid Client-Id","ErrorDetails":"X-DIGIKEY-Client-Id invalid for requested resource","RequestId":"6c3c9f5e-2fee-424c-98b4-3a4f13115164","ValidationErrors":[]}
 (kicost.distributors - api.py:92)

@clwe
Copy link

clwe commented Oct 18, 2024

Again, commenting out the portion of code that calls the sandbox api in api.py fixes it for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants