Search code examples
amazon-web-servicesaws-lambdaaws-lambda-edge

How to extract bearer token in using boto3 python 3.8 in cloudfront request and use it in another query


How can I extract the bearer token in incoming cloudfront request and use it in another get request.

curl -X GET \
  https://domain/api/files/7d0ab8ef-9061-4458--de79a2c9e436 \
  -H 'Authorization: Bearer eTA' \
  -H 'Cache-Control: no-cache' \
  -H 'Postman-Token: token'

use the bearer token as jwt in the following request

 in phython domain.com/service/api/files/7d0ab8ef-9061-4458--de79a2c9e436

which gives me the following response :

https://domain/file-service/api/files/7d0ab8ef-9061-4458-b97a-de79a2c9e436

{
    "id": "7d0ab8ef-9061-4458-b97a-de79a2c9e436",
    "uploadId": "-9b68-44bd-864a-cd9a40d601ba",
    "consumerId": "-97d1-11ea-bb37-0242ac130002",
    "metadata": {
        "fileName": "somefile.docx",
        "fileSize": 1000,
        "mimeType": "application/msword"
    },
    "objectKey": "2020-04-31/ju-28fc-4d7c-b086-66c15eb311e7.docx",
    "status": "PENDING"
}

My lambda code looks like this

import json

def lambda_handler(event, context):
    # TODO implement
    request = event['Records'][0]['cf']['request']
    print(request['headers'])
    print(response)

Solution

  • You would add this as a Lambda@Edge function for the viewer request event.

    The Lambda@Edge would look like the following

    import json
    import requests
    
    def lambda_handler(event, context):
    
        request = event['Records'][0]['cf']['request']
        print (request)
        print(request['headers'])
        print(request['origin']['s3']['domainName'])
        token = request['headers']['cookie'][0]['value'].partition("=")[2]
        print (token)
        print(type(request['uri']))
        cosumer_id = request['uri'].rpartition('/')[-1]
        print (cosumer_id)
    
        #Take the token and send it somewhere
        token_response = requests.get(url = 'https://url/api/files/'  + cosumer_id, headers = {'Authorization': 'Bearer ' + token}) 
    
        print (token_response.request)
        print (token_response)
        print (token_response.text)
        data = token_response.json() 
        objectKey = data["objectKey"]
        print (objectKey)
    
    
        return request
    

    Assuming you're using the requests library you would be able to retrieve the response like this

    object = token_response.objectKey