Maxcot
Maxcot

Reputation: 1617

How to pass an (OAuth) access token in an API call?

I'm struggling with an API call using OAuth 2.0 and Python.

The flow, as I understand it, should be this:

  1. Request a token using a client_id (API Key) and a client_secret
  2. If successful, receive an access token and refresh token.
  3. Make the desired API call, using the access_token.

Now my problem is that step 3 doesn't work.

#requesting access token
URL='https://www.geni.com/platform/oauth/request_token?client_id=...&client_secret=......&grant_type=client_credentials'
response = requests.post(OAuthURL)
listReponse = json.loads(response.text)
print ("access_token acquired: ", listReponse['access_token'])

This is just fine. With guidance from James, the token is used in the headers, not as a query parameter.

# so this won't work
URL = "https://www.geni.com/api/profile-122248213/immediate-family?access_token="+listReponse['access_token']

So

URL = "https://www.geni.com/api/profile-122248213/immediate-family"

theHeaders={'Content-Type':'application/json',
            'Authorization': 'Bearer {}'.format(theAccessToken)}
print ('Headers:', theHeaders)

>>> Headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer:aaaaa3LRm6frS4FwZvB3ZMZwdKVNMCEBpBvlFwbT'}

Produces this

{'error': {'type': 'OAuthException', 'message': 'Invalid access token'}}

yet when I validate the token using a different API endpoint for that purpose, I get

{"result":"OK"}

So best I can determine, the formatting of the headers is the problem. What am I doing wrong?

theHeaders={'Content-Type':'application/json',
            'Authorization': 'Bearer {}'.format(theAccessToken)}

Upvotes: 2

Views: 5644

Answers (1)

James McPherson
James McPherson

Reputation: 2576

Thanks @Maxcot for the confirmation. Following on from my initial comment about the Authorization element being a request header rather than query param, there's another niggle.

In the printed headers

>>> Headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer:aaaaa3LRm6frS4FwZvB3ZMZwdKVNMCEBpBvlFwbT'}

there's an error. The Authorization header must be formed like this:

Authorization: Bearer $yourBearerToken

so you're mostly right but have an extraneous :. Using your example token text, the header should be

Authorization: Bearer aaaaa3LRm6frS4FwZvB3ZMZwdKVNMCEBpBvlFwbT

If you were exporting this as a shell variable, it would be

export AUTH="Authorization: Bearer aaaaa3LRm6frS4FwZvB3ZMZwdKVNMCEBpBvlFwbT"

but since you're using this in Python, the headers are

headers = {
    "Content-type": "application/json",
    "Authorization": "Bearer aaaaa3LRm6frS4FwZvB3ZMZwdKVNMCEBpBvlFwbT"
}

Upvotes: 1

Related Questions