I am new to implementing security authentication on rest api. I am trying to implement oauth2 authorization from aws cognito user pool.
from flask import Flask,jsonify,render_template,request
import requests
import socket
app = Flask(__name__)
name='Umesh'
App_client_id = 'cleintId'
App_client_secret = 'clientSecret'
url = 'https://myurl.auth.eu-west-1.amazoncognito.com'
targetApi = 'https://myTargetApi/v1/product'
class setTokenCache():
cache=''
obj= setTokenCache()
#print("Acces token is ", obj.cache)
@app.route('/login')
def index():
try:
grant_type = 'client_credentials'
response = requests.post(url + '/oauth2/token',
auth=(App_client_id, App_client_secret),
data={'grant_type': grant_type, 'client_id': App_client_id,
'client_secret': App_client_secret})
print("Staus code", response)
if response.status_code!=200:
return "You are not authenticated"
else:
result = response.json()
obj.cache = result['access_token']
print("Access token is",obj.cache)
return "You are Logined"
except socket.gaierror as e:
print("Unable to get the r")
Here is the api returns #'You are Logined', if its authenticated with the access token just generated.Just consider its a login part.
Now i have this API, where i want to get the valid response using the above generated access token.
@app.route('/getProductDetails', methods=['GET', 'POST'])
def productDetails():
print("Access token is",obj.cache)
headers = {'Authorization': 'Bearer ' + accessToken, 'Accept': 'application/json'}
try:
response = requests.get(targetApi, headers=headers)
return response.json()
except socket.gaierror as e:
print("Unable to get the r")
Here i need to pass the #accessToken in order to get the valid response or otherewise it will return, #unauthrized
Now i would like to know how should i implement this security over this api in such way that
http://127.0.0.1:5000/getProductDetails
OR 2. How to ensure that how browser/client would consume the same token while navigating from API 1 to API till it expired
Appreciate if anybody can help on this?
In terms of Cognito token validation there is some sample NodeJS code below and you should find a library for your programming language. Also the below online tool can be useful for understanding the validation process: