amplify-cli icon indicating copy to clipboard operation
amplify-cli copied to clipboard

Amplify API returning CORS error

Open sayu-agiliad opened this issue 4 years ago • 14 comments

Before opening, please confirm:

  • [X] I have installed the latest version of the Amplify CLI (see above), and confirmed that the issue still persists.
  • [X] I have searched for duplicate or closed issues.
  • [X] I have read the guide for submitting bug reports.
  • [X] I have done my best to include a minimal, self-contained set of instructions for consistently reproducing the issue.
  • [X] I have removed any sensitive information from my code snippets and submission.

How did you install the Amplify CLI?

npm

If applicable, what version of Node.js are you using?

16.14.2

Amplify CLI Version

8.0.2

What operating system are you using?

Windows 10

Did you make any manual changes to the cloud resources managed by Amplify? Please describe the changes made.

No manual changes done.

Amplify Categories

auth, function, api

Amplify Commands

add

Describe the bug

I added an API with below configuration: image

I invoke the API like this image

I get error 403 when I invoke the API in the context of an authenticated user. image

Expected behavior

Error should not occur.

Reproduction steps

  1. Create a next js project
  2. Add Auth with user groups.
  3. Add API with above settings.
  4. Invoke API

GraphQL schema(s)

Not applicable

Log output

No response

Additional information

No response

sayu-agiliad avatar May 16 '22 11:05 sayu-agiliad

Hey @sayu-agiliad :wave: thanks for raising this! The example you provided will work when using a custom authorizer leveraging Cognito User Pools, however when restricting routes to auth users, guests, and groups from the CLI we will be authenticating with IAM. Can you try calling your API without providing a custom auth header?

josefaidt avatar May 16 '22 13:05 josefaidt

Hey @josefaidt , I am sorry I don't quite follow you. If I remove the custom auth header, I receive the following error image

Could you point me to a documentation for "authenticating with IAM" part which I could use.

sayu-agiliad avatar May 16 '22 16:05 sayu-agiliad

Hey @sayu-agiliad here is the documentation page for fetching data from our REST API https://docs.amplify.aws/lib/restapi/fetch/q/platform/js/

I have a few follow-up questions:

  • are you using any overrides?
  • are you using a custom authorizer?

josefaidt avatar May 16 '22 17:05 josefaidt

Hey @sayu-agiliad here is the documentation page for fetching data from our REST API https://docs.amplify.aws/lib/restapi/fetch/q/platform/js/

I have a few follow-up questions:

  • are you using any overrides? No I am not using any overrides.
  • are you using a custom authorizer? No I am not using a custom authorizer.

Thank you. I have been following this guide, but facing the error when I create restricted API. I am trying to develop a NextJS application, and I would like the API to be restricted to only users belonging to a particular group.

I have confirmed that If I do not restrict API access, I am able to invoke the API successfully.

sayu-agiliad avatar May 16 '22 17:05 sayu-agiliad

Hey @sayu-agiliad can you share a snippet of how you're calling the API from the frontend? Also, do you have CORS headers applied to your Lamdba function's response? In the following example authenticated users are allowed to read the endpoint, where members of the admins group are able to create and read

lambda

/**
 * @type {import('@types/aws-lambda').APIGatewayProxyHandler}
 */
exports.handler = async (event) => {
  console.log(`EVENT: ${JSON.stringify(event)}`)
  return {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers': '*',
    },
    body: JSON.stringify('Hello from Lambda!'),
  }
}

Sample frontend code (using Next.js)

// src/pages/hello.jsx
import { useState, useEffect } from 'react'
import { API } from 'aws-amplify'
import awsExports from '../aws-exports'

const [{ name: API_NAME }] = awsExports.aws_cloud_logic_custom

export default function HelloPage(props) {
  const [data, setData] = useState()

  async function read() {
    setData(await API.get(API_NAME, '/hello', { response: true }))
  }
  async function create() {
    setData(await API.post(API_NAME, '/hello', { response: true }))
  }

  useEffect(() => {
    read()
  }, [])

  return (
    <div>
      <button onClick={read}>read</button>
      <button onClick={create}>create</button>
      <pre>
        <code>{JSON.stringify(data, null, 2)}</code>
      </pre>
    </div>
  )
}

In the end, we should receive a 403 error when attempting to make a POST call while signed in as user image

josefaidt avatar May 16 '22 19:05 josefaidt

  1. Yes, I do have CORS header applied to my Lambda functions response.
  2. My front end code looks like below
  async function checkLogin(){
  console.log('Access token', (await Auth.currentSession()).getAccessToken().getJwtToken())
  console.log('ID Token', (await Auth.currentSession()).getIdToken().getJwtToken())
  let apiName = 'NotificationAPI';
  let path = '/items';
  let myInit = {
      headers: {
            Authorization: `${(await Auth.currentSession()).getAccessToken().getJwtToken()}`
      }
  }
  const result = await API.get(apiName, path,myInit)
}

If I invoke the API like below: const result = await API.get(apiName, path,{result:true})

I get image

Please note that the API was created with below settings:

? Select from one of the below mentioned services: REST
√ Select the REST API you want to update: · NotificationAPI
√ What would you like to do? · Update path
? Select the path to edit /
√ Provide a path (e.g., /book/{isbn}): · /
√ Choose a Lambda source · Use a Lambda function already added in the current Amplify project
√ Choose the Lambda function to invoke by this path · NotificationLambda
√ Restrict API access? (y/N) · yes
√ Restrict access by: · Auth/Guest Users
√ Who should have access? · Authenticated users only
√ What permissions do you want to grant to Authenticated users? · create, read, update, delete

I want the API to be accessible to all Authenticated users.

sayu-agiliad avatar May 17 '22 04:05 sayu-agiliad

Hey @sayu-agiliad do you receive any errors when attempting to call the API without the init with the Authorization header?

 async function checkLogin() {
  let apiName = 'NotificationAPI';
  let path = '/items';
  const result = await API.get(apiName, path)
}

josefaidt avatar May 17 '22 13:05 josefaidt

@josefaidt I get the below error if I do not use the init. image

In developer tools, I see the error details as below: image

sayu-agiliad avatar May 17 '22 13:05 sayu-agiliad

Hey @sayu-agiliad do you see an authorization header attached to the request? image

And we should see IAM as the authorization set on our API Gateway route image

josefaidt avatar May 17 '22 13:05 josefaidt

@josefaidt The API Gateway has the Authorization set to AWS IAM as in your screenshot. However, my request headers does not contain the authorization header as can be seen below. image

sayu-agiliad avatar May 17 '22 13:05 sayu-agiliad

Hey @sayu-agiliad thank you for clarifying that is interesting. Can you post the dependencies used in your app's package.json and how you're configuring Amplify in the frontend (e.g. Amplify.configure(awsExports)? Are there any logs in your browser that stand out? We can add Amplify.Logger.LOG_LEVEL = 'DEBUG' to print more verbose logs as well

josefaidt avatar May 17 '22 14:05 josefaidt

@josefaidt package.json dependencies.

    "@emotion/react": "^11.9.0",
    "@emotion/styled": "^11.8.1",
    "@mui/material": "^5.6.2",
    "aws-amplify": "^4.3.20",
    "cross-env": "^7.0.3",
    "jest-environment-jsdom": "^28.0.0",
    "next": "12.1.5",
    "react": "18.0.0",
    "react-dom": "18.0.0",
    "react-redux": "^8.0.1"
  },
  "devDependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.1.1",
    "cypress": "^9.5.4",
    "eslint": "8.13.0",
    "eslint-config-next": "12.1.5",
    "jest": "^28.0.0"
  }

my aws-exports.js

const awsmobile = {
    "aws_project_region": "us-east-1",
    "aws_cognito_identity_pool_id": "us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "aws_cognito_region": "us-east-1",
    "aws_user_pools_id": "us-east-1_1re9cJyj1",
    "aws_user_pools_web_client_id": "xxxxxxxxxxxxxxxxxxxxxxxxx",
    "oauth": {
        "domain": "dev-cat-csm-dev.auth.us-east-1.amazoncognito.com",
        "scope": [
            "phone",
            "email",
            "openid",
            "profile",
            "aws.cognito.signin.user.admin"
        ],
        "redirectSignIn": "http://localhost:3000/signin/,http://localhost:3000/signin/",
        "redirectSignOut": "http://localhost:3000/signout/",
        "responseType": "code"
    },
    "federationTarget": "COGNITO_USER_POOLS",
    "aws_cognito_username_attributes": [
        "EMAIL"
    ],
    "aws_cognito_social_providers": [],
    "aws_cognito_signup_attributes": [
        "EMAIL",
        "NAME",
        "PHONE_NUMBER"
    ],
    "aws_cognito_mfa_configuration": "OFF",
    "aws_cognito_mfa_types": [
        "SMS"
    ],
    "aws_cognito_password_protection_settings": {
        "passwordPolicyMinLength": 8,
        "passwordPolicyCharacters": []
    },
    "aws_cognito_verification_mechanisms": [
        "EMAIL"
    ],
    "aws_cloud_logic_custom": [
        {
            "name": "AdminQueries",
            "endpoint": "https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev",
            "region": "us-east-1"
        },
        {
            "name": "NotificationAPI",
            "endpoint": "https://yyyyyyyyyyy.execute-api.us-east-1.amazonaws.com/dev",
            "region": "us-east-1"
        }
    ]
};

export default awsmobile;

I configure Amplify.configure({ ...awsmobile, ssr: true });

One thing I noticed, is that I am using const { Auth } = withSSRContext();

should i just import the Auth rather than getting it from SSRContext ?

sayu-agiliad avatar May 17 '22 14:05 sayu-agiliad

@josefaidt I did some change to my applicaiton. I realized that while setting up AUTH, I had selected the "Authorization Grant" flow. I updated it to use "Implicit Flow". With this change, I was able to see the header which you had shared. 👍

Also, I had created the lambda function as a serverless expressjs function with paths as /item. However, while creating the API I had just included the root path / assuming (quite incorrectly) that it would resolve to the correct handler in the expressJS app.

So when my app requested a GET on /item it failed, but a GET on / succeeded with the correct response. So I updated API to include the /item path and it worked.

Please let me know if above is as per intended design.

sayu-agiliad avatar May 17 '22 17:05 sayu-agiliad

Hey @sayu-agiliad thanks for the update! And that makes sense! I ran through a few more attempts with AdminQueries and the ssr: true prop to no avail. I'm glad to hear you're back up and running though! I'll close this issue for now, however if you run into a similar problem feel free to reply back to this thread and we can re-open to investigate further 🙂

josefaidt avatar May 17 '22 17:05 josefaidt