Search code examples
amazon-web-servicesgraphqlboto3aws-amplifyaws-appsync

How to authenticate requests made to AWS AppSync in Python?


I have a website with a backend of AWS Amplify. For a post-payment function, I am creating a lambda function to update the database. I am trying to query certain fields with the help of AppSync and then run a mutation. This is my function code:

import json
import boto3
import os
import decimal
import requests
from requests_aws4auth import AWS4Auth

def lambda_handler(event, context):

    dynamoDB = boto3.resource('dynamodb', region_name='ap-northeast-1')

    // load event data (hidden)

    userid = sentData.get("userid")
    slots = sentData.get("slots")

    url = os.environ.get("AWS_GRAPHQL_API_ENDPOINT")
    api_key = os.environ.get("AWS_GRAPHQL_API_KEY")

    session = requests.Session()

    query = """
    query MyQuery {
        getUserPlan(id: "9ddf437a-55b1-445d-8ae6-254c77493c30") {
            traits
            traitCount
        }
    }
            """

    credentials = boto3.session.Session().get_credentials()
    session.auth = AWS4Auth(
        credentials.access_key,
        credentials.secret_key,
        'ap-northeast-1',
        'appsync',
        session_token=credentials.token
    )

    # response = session.request(
    #     url=url,
    #     method="POST",
    #     json={"query": query},
    #     headers={"Authorization": api_key},
    # )

    # response = requests.post(
    #     url=url,
    #     json={"query": query},
    #     headers={"x-api-key": api_key}
    # )

    response = session.request(
        url=url,
        method="POST",
        json={"query": query},
    );

    print(response.json())

    return {
        "statusCode": 200,
    }

I get the following error when I execute the function: {'data': {'getUserPlan': None}, 'errors': [{'path': ['getUserPlan'], 'data': None, 'errorType': 'Unauthorized', 'errorInfo': None, 'locations': [{'line': 3, 'column': 9, 'sourceName': None}], 'message': 'Not Authorized to access getUserPlan on type UserPlan'}]}

I have referred to this and this. I have tried their solutions but they haven't worked for me. I have confirmed that all the environment variables are working properly and even added the local aws-cli iam user to the custom-roles.json file for admin privileges by Amplify. When I was trying with the API Key, I made sure that it hadn't expired as well.


Solution

  • I figured out how to fix it. I had to create a function through the amplify-cli, give it access to the api, push the function and then add the name of the role to adminRoleNames in custom-roles.json