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).

  • 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

      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

        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.

    • sparsht's avatar
      sparsht
      Guide

      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