Search code examples
python-3.xsecurityflaskoauth-2.0amazon-cognito

How to handle the token validation in backend


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

API 1 Login

Here is the api returns #'You are Logined', if its authenticated with the access token just generated.Just consider its a login part.

API 2 Accessing the productDetails

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

Expected:

Now i would like to know how should i implement this security over this api in such way that

  1. It should consume the above created accessToken till it expired in order to get the valid response from the api
 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?


Solution

  • 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: