Forum Discussion

fcaelen's avatar
fcaelen
Mentor
6 years ago

OAuth in python

Hi!

I am writing a small script in Python to retrieve data from the REST API. For instance, I need to do some v2 requests like "SELECT id,post_time,subject,author,status,body,kudos,labels FROM messages WHERE board.id = 'myBoard' AND depth = 0".

So, I need to get access to some sections and I am trying to use the OAuth 2.0 Authorization but I get an error:

oauthlib.oauth2.rfc6749.errors.MissingTokenError: (missing_token) Missing access token parameter.

Here is my code:

from oauthlib.oauth2 import BackendApplicationClient
from requests.auth import HTTPBasicAuth

client_id = 'myClientID'
client_secret = 'myClientSecret'
auth = HTTPBasicAuth(client_id, client_secret)
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url='https://myCommunity/auth/oauth2/authorize', auth=auth)
print(token)

Any idea?

Thanks!

 

Florent

  • I finally found the issue 😀 In the header, the client ID should be declared as 'client-id' and not 'client_id' as it is in the body. The other issue was that the code expires quickly and I tried to use it during a too long time which made my tries useless (I tried before 'client-id' without success because the code had already expired).

10 Replies

  • Hi fcaelen ,

    First of all the token URL isn't correct and incomplete as well.

    For OAuth 2.0, You need to follow the steps mentioned

    1. hit the following URL manually or can make a GET request script :- 

    https://myCommunity/auth/oauth2/authorize?client_id=[CLIENT_ID]&response_type=code&redirect_uri=[REDIRECT_URI]

    [REDIRECT_URI] is the URL you provide while registering your App under ADMIN>SYSTEM>API Apps .

    It will redirect to the the provided [REDIRECT_URI] with code and tenant ID.

    For Example -

    https://[REDIRECT_URI]?code=[authorization_code]&tenant=[tenant_Id]

    Fetch the "authorization code" which is URL Encoded (decode it into string) and pass it as described below in Step 2.

    2. Make a POST Request to the given URL. Find the sample code below.

    import requests
    ACCESS_TOKEN_URL = "https://api.lithium.com/auth/v1/accessToken"
    requests.post(
    ACCESS_TOKEN_URL,
    headers = {"Content-type" : "application/json", "client_id" : "[CLIENT_ID]"}, data = {     "code" : "[authorization_code]",     "client_id" : "[CLIENT_ID]",     "client_secret" : "[CLIENT_SECRET]",      "redirect_uri" : "[REDIRECT_URI]",      "grant_type" : "authorization_code" } )

     

    ACCESS_TOKEN_URL for stage will be "https://api.stage.lithium.com/....."

    Sample Response Body on success

    { 
    "response": {
    "status": "success",
    "message": "OK",
    "http_code": 200,
    "data": {
    "access_token": "o5IV0yIiNDj/5lNJ6doJh08LX6SsDwtkDXDVmhGvRtI=",
    "expires_in": 86400,
    "lithium_user_id": "2d8c95ed-21dc-4ba6-ab9f-d3eff9c928ce",
    "refresh_token": "XAAWIWKr38W33SlqYooR9OEJW0um9DoyB/o843rdIxk=",
    "token_type": "bearer"
    }
    }
    }

    "access_token" will be used to make the calls.

    Accept it as solution if it solves your query.

    Thanks

  • fcaelen's avatar
    fcaelen
    Mentor
    6 years ago

    thanks sparsht :smileyhappy:

    but even step 1. doesn't work. I even tried in a browser

    https://myCommunity/auth/oauth2/authorize?client_id=[CLIENT_ID]&response_type=code&redirect_uri=[REDIRECT_URI]

    with my client id and the redirect URI of my API App but I get an error:

     

    Any idea?

    I have also tried different redirect URIs: https://myCommunity.com/ or https://myCommunity.com/getaccessToken but still the same.

    thanks!

  • sparsht's avatar
    sparsht
    Guide
    6 years ago

    fcaelen Hi there ! It seems like you have missed something or I haven't been able to explain properly.

    https://myCommunity.com/auth/oauth2/authorize?client_id=LFE0UbsMFc9uDhsZLu03q4565ZZjO78svn7RFDRs=&response_type=code&redirect_uri=https://wt-c12345.sandbox.auth0-extend.com/lithium-integrate

     Make sure sample code is like this. I have tried and it's working fine for me. ID and Redirect URI should be the same as mentioned in API App under  ADMIN>SYSTEM>API Apps.

  • fcaelen's avatar
    fcaelen
    Mentor
    6 years ago

    Yes, I have replaced the Community URL, the client id and the redirect URI but I get the error.

  • fcaelen's avatar
    fcaelen
    Mentor
    6 years ago

    hi sparsht. I could finally get the code, my mistake was that I had to encode my client id (it ends with a "=").

    So, I tried the sample code

    ACCESS_TOKEN_URL = "<a href="https😕/eu.api.lithium.com/auth/v1/accessToken" target="_blank">https😕/eu.api.lithium.com/auth/v1/accessToken</a>"
    r = requests.post(
    ACCESS_TOKEN_URL,
    headers = {"Content-type" : "application/json", "client_id" : client_id},
    data = {
    "code" : code,
    "client_id" : client_id,
    "client_secret" : client_secret,
    "redirect_uri" : redirect_uri,
    "grant_type" : "authorization_code"
    }
    )

    but I get an error saying it doesn't support Json:

    400 Bad Request
    {"code":400,"message":"Unable to process JSON"}

     

    Any idea? thanks

  • sparsht's avatar
    sparsht
    Guide
    6 years ago

    Hi fcaelen ,

    The error indicates that the JSON being sent in the body is malformed or not in proper format. Please check the JSON being sent using json Validator or similar tool.

    Also replace your access token variable with the one mentioned below.

    ACCESS_TOKEN_URL = "<a href='https/eu.api.lithium.com/auth/v1/accessToken' target='_blank'>https/eu.api.lithium.com/auth/v1/accessToken</a>"

     Check your "data" value as well if the above doesn't solve your problem.

     

  • fcaelen's avatar
    fcaelen
    Mentor
    6 years ago

    Thanks sparsht I checked my "data" and I found nothing wrong.

    I tried also a curl request using a REST client in my browser:

    curl -X POST -k -H 'client_id: myID' -i 'https😕/eu.api.lithium.com/auth/v1/accessToken' --data 'code=myCode&client_id=myID&client_secret=mySecret&redirect_uri=https%3A%2F%2FmyCommunity.com&grant_type=authorization_code'

     

     

    and I get a 500 error "There was an error processing your request"

  • fcaelen's avatar
    fcaelen
    Mentor
    6 years ago

    I finally found the issue 😀 In the header, the client ID should be declared as 'client-id' and not 'client_id' as it is in the body. The other issue was that the code expires quickly and I tried to use it during a too long time which made my tries useless (I tried before 'client-id' without success because the code had already expired).

  • sparsht's avatar
    sparsht
    Guide
    6 years ago

    In the above given solution or steps mentioned. Make sure to replace "client_id" with "client-id" in the header only. 🙂

  • For those who are confused like myself , I am consolidating the above steps mentioned by sparsht and fcaelen after working out all the issues that I faced:


    1. hit the following URL manually or can make a GET request script :-

     

    https://mycommunityurl.com/auth/oauth2/authorize?client_id=[CLIENT_ID]&response_type=code&redirect_uri=[REDIRECT_URI]

     

    • Encode the [CLIENT_ID] to URL encoded format
    • [REDIRECT_URI] is the URL you provide while registering your App under ADMIN>SYSTEM>API Apps .

    It will redirect to the the provided [REDIRECT_URI] with code and tenant ID.

    For Example -

     

    https://[REDIRECT_URI]?code=[authorization_code]&user-id=[userid]&tenant=[tenant_Id]

     


    Fetch the "authorization code" which is URL Encoded (decode it into string) and pass it as described below in Step 2.

    2. Make a POST Curl Request to the given URL. Find the sample code below (for windows cmd users).

     

    curl -X POST ^
    https://mycommunityurl.com/api/2.0/auth/accessToken ^
    -H "Content-Type: application/json" ^
    -H "client-id: [CLIENT_ID]" ^
    -d "{ \"client_id\":\"[CLIENT_ID]\", \"client_secret\":\"[CLIENT_SECRET]\", \"grant_type\":\"authorization_code\", \"redirect_uri\":\"[REDIRECT_URI]\", \"code\":\"[Decoded_authorization_code from step 1]\" }"

     

    • [CLIENt_ID] , [CLIENT_SECRET],[REDIRECT_URI] are all that can be obtained while registering your App under ADMIN>SYSTEM>API Apps .

    Sample Response Body on success

     

    {
    "response": {
    "status": "success",
    "message": "OK",
    "http_code": 200,
    "data": {
    "access_token": "o5IV0yIiNDj/5lNJ6doJh08LX6SsDwtkDXDVmhGvRtI=",
    "expires_in": 86400,
    "lithium_user_id": "2d8c95ed-21dc-4ba6-ab9f-d3eff9c928ce",
    "refresh_token": "XAAWIWKr38W33SlqYooR9OEJW0um9DoyB/o843rdIxk=",
    "token_type": "bearer"
    }
    }
    }

     

    "access_token" will be used to make the calls.

    3. Run the LIQL queries via script or curl using the access token from step 2.

    Sample Python Code below:

     

    import requests
    ACCESS_TOKEN_URL = "https://mycommunityurl.com/api/2.0/search?q=SELECT%20*%20FROM%20users"
    x=requests.get(
    ACCESS_TOKEN_URL,
    headers = {"Content-type" : "application/json", "client-id" : "[CLIENT_ID]","Authorization":"Bearer [Access_TOKEN]"},
    
    )
    x.json()

     

    Sample Curl Code (Windows CMD Users) below:

     

    curl --location --request GET "https://mycommunityurl.com/api/2.0/search?q=SELECT%20*%20FROM%20users" ^
    -H "content-type: application/json" ^
    -H "Authorization: Bearer [Access_Token]" ^
    -H "client-id: [CLIENT_ID]"

     

    • Make sure to include the 'Bearer' keyword in the authorization header as shown in the sample code.

    Full Kudos and credits to fcaelen and sparsht