Search code examples
pythonpython-requestsauth0urlencode

Auth0 API can't see URI parameter submitted with Python Requests


I'm trying to do an authentication against Auth0 from a Python script using the PKCE authentication flow, and I'm getting an error that Auth0 can't see exactly one of my URI parameters.

<<CAPITAL LETTERS>> represent missing constants related to the authentication exchange being tested.

import requests
import urllib.parse

def process_auth_callback(authorization_code, callback_uri):
    payload = {
        'grant_type': 'authorization_code',
        'client_id': <<AUTH CLIENT ID>>,
        'code_verifier': <<CODE VERIFIER>>,
        'code': authorization_code,
        'redirect_uri': urllib.parse.quote(callback_uri)
        }
    r = requests.post('https://<<APP ID>>.us.auth0.com/oauth/token', data=payload)
    print(r.request.body)
    print(r.text)

process_auth_callback(<<AUTHORIZATION CODE>>, 'http://localhost:1234/login')

I get the error back from Auth0's API: {"error":"unauthorized_client","error_description":"The redirect URI is wrong. You sent null//null, and we expected http://localhost:1234"}

However, the request body prints as the following: grant_type=authorization_code&client_id=<<AUTH CLIENT ID>>&code_verifier=<<CODE VERIFIER>>&code=<<AUTHORIZATION CODE>>&redirect_uri=http%253A%2F%2Flocalhost%253A1234%2Flogin

This appears to include the correct redirect URI, so I'm not sure why the API is reporting null//null. Is this an issue with how I'm using requests? Something else?


Solution

  • Ah, I found my own answer not long after.

    The key is the %253A in the URI encoding in the outgoing request body. (See this answer) Python's requests library is already URI-encoding the parameters, so my URI encoded urllib.parse.quote(callback_uri) is then being encoded again during the data preprocessing prior to send. Auth0's API is unable to parse this and processes it as null//null.