python-3.xoauth-2.0base64python-requestsfitbit

Python OAuth 2.0 --> Fitbit API "invalid_client" error


I am attempting to use OAuth 2.0 with the Fitbit web API, however I keep getting an error sent back to me.

The error I get is:

{"errors":[{"errorType":"invalid_client","message":"Invalid authorization header format. The client id was not provided in proper format inside Authorization Header. Received authorization header = Basic XXXXXXXXXXXXXXXXXXXXXXX, received client encoded id = XXXXXX. Visit https://dev.fitbit.com/docs/oauth2 for more information on the Fitbit Web API authorization process."}],"success":false}

I have searched the web for hours and the most common cause of this type of error is not having "Basic" spelt correctly, but I do not think this is the case here as the error more specifically states that the client_id was not provided in the proper format.

Below is the relevant parts of my code:

#These are the secrets etc from Fitbit developer
client_id = "XXXXX"
client_secret = "XXXXXXXXXXXXXXXXXXX"

# Encode OAuthTwoClientID and ClientOrConsumerSecrets and convert from strings to bytes
b64id = base64.b64encode(client_id.encode())
b64secret = base64.b64encode(client_secret.encode())

# Pass encoded ID and Secrets to header and decode 
header = {'Authorization': 'Basic ' + b64id.decode() + ":" + b64secret.decode(), 
'Content-Type': 'application/x-www-form-urlencoded'}

# Start the request
req = requests.get(TokenURL,BodyURLEncoded, headers=header)

Any ideas?


Solution

  • You got the Authorization header part wrong. Instead of

    'Basic ' + b64id.decode() + ":" + b64secret.decode(),
    

    You need to concatenate first and base64-encode second

    secret = client_id + ":" + client_secret
    b64secret = base64.b64encode(secret.encode())
    header = { 'Authorization': 'Basic ' + b64secret.decode() }
    

    This is described in the docs in the chapter "Access Token Request".