awslabs / aws-mobile-appsync-sdk-js

JavaScript library files for Offline, Sync, Sigv4. includes support for React Native
Apache License 2.0
921 stars 266 forks source link

Make an AppSync call using Cognito credentials #738

Closed jdanielsyeah closed 1 year ago

jdanielsyeah commented 1 year ago

Note: If your issue/feature-request/question is regarding the AWS AppSync service, please log it in the official AWS AppSync forum

Do you want to request a feature or report a bug? Neither - I have a question: How do I set up AppSync in a Node.JS Lambda that is being triggered from an Amplify client? What is the current behavior? I get the following error:

                {
                    "errorType": "UnauthorizedException",
                    "message": "Valid authorization header not provided."
                }

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem.

I currently have AppSync working when set up with IAM:

import {
  AUTH_TYPE,
  AWSAppSyncClientOptions,
  AWSAppSyncClient,
} from "aws-appsync";
import { config, Credentials } from "aws-sdk";

const credentials = config.credentials as Credentials;

// GraphQL client config
const appSyncClientConfig: AWSAppSyncClientOptions = {
  url: APPSYNC_URL, // from AppSync console.
  region: "eu-west-2",
  auth: {
    type: AUTH_TYPE.AWS_IAM as const,
    credentials: credentials as Credentials,
  },
  offlineConfig: {
    keyPrefix: "public",
  },
  disableOffline: true,
};

const appSyncClient = new AWSAppSyncClient(appSyncClientConfig); // Initialise the AppSync client

So in order to adapt it to use Cognito User Pools, it looks like the auth prop in the above should be updated to:

    auth: {
      type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS as const,
      jwtToken: jwtToken,
    },

But I don't know how to set the jwtToken for it not to return an error. Presumably it is set with some values from the event object, but I can't work it out?

What is the expected behavior? A successful AppSync call to update a DynamoDB database Which versions and which environment (browser, react-native, nodejs) / OS are affected by this issue? Did this work in previous versions? nodejs: "aws-appsync": "^4.1.7", "aws-sdk": "^2.1205.0", "dotenv": "^16.0.2", "fs": "^0.0.1-security", "graphql-tag": "^2.12.6", "node-fetch": "^2.6.7", "serverless-plugin-aws-alerts": "^1.7.5"

iartemiev commented 1 year ago

Hi, you can easily retrieve the JWT if you use the Amplify Auth category for authentication.

Here's a link to the docs: https://docs.amplify.aws/lib/auth/advanced/q/platform/react-native/#retrieve-jwt-tokens

misha-erm commented 7 months ago

Hello, @iartemiev sorry for bringing up the closed issue but what if I'm not using Amplify? I use AppSync with cdk on my backend and trying to setup apollo on client. Is there a way to get Cognito token without using aws-amplify/* packages?

P.S. also the link seems to be lost (