Wednesday, March 9, 2022

Example of Oracle ORDS with OAuth 2 from Python/Flask

Python/Flask with ORDS Authentication

The following example shows Python/Flask code to get the authentication token and accessing the ORDS API by passing the token as part of the GET REQUEST. The two main steps involved in this  are 
Use your client ID and client secret to obtain an auth token. 
You will add the auth token to the header of each ORDS API request.

# Values that you need to provideclient_id = "<your client id>"client_secret = "<your client secret>
from flask import Flask, render_template, redirect, request, session
import requests
import IdcsClient
import json
import base64

@app.route('/Python_flask',  methods=["POST","GET"])
def restapi():

/* part of SSO -- If you have session token, then run the secure ORDS application  -- not shown in this example */
    id_token = (session.get("id_token", None))
    if id_token is None:
       return render_template('login.html')

    /* Get the client_id and Client_secret for ORDS with Oauth2 protection */

    client_id = 'xtcLYtHJfz6ejruDsCcZjQ'
    client_secret = 'yzOfoU07DQmOuYQf9jlOQ'
    grant_type = "client_credentials"

    #set the data
    data = {
       "grant_type": grant_type,
       "client_id": client_id,
       "client_secret": client_secret
     }

    #get the token for protected ORDS 

    # POST call with AUTH and DATA to get ORDS token
    auth_response = requests.post(fullstack_auth_url, auth=(client_id,client_secret),data=data)

    auth_response_json = auth_response.json()

    auth_token = auth_response_json["access_token"]

    auth_token_header_value = "Bearer %s" % auth_token

    auth_token_header = {"Authorization": auth_token_header_value}

    
    # URL link to get the ORDS.

    #pass the token along with the URL as GET request
    response = requests.get(url_link , headers=auth_token_header)

    jsondata = response.json()
    jsonStr = json.dumps(jsondata)
    pythonObj = json.loads(jsonStr)


    
    /* 


       the processing of ORDS data goes here.


    */ 
     
     #render the processed data into Flask html page.
    return render_template('bar_chart.html', title='Compound Interest rate of '+ rate + '%', max=max, min=min ,labels=ages, values=balances)





 

No comments:

Post a Comment

Feedback welcome