Amplify gen 2: lambda mutation `No federated jwt` error

0

I have an Amplify app using Cognito for userpool authentication. Once a user has signed up and used the code sent via email (all Cognito functionality), they are passed to a custom form where additional information is captured. On submit a lambda function is executed that should:

  1. Create a group in Cognito
  2. Add the user to the group
  3. Create a record in a DynamoDB table and use the group name created in step 1. in a "writeGroups" fields referenced in the schema for allow.groupsDefinedIn('writeGroups')

The lambda function deploys nicely as part of my sandbox, and permissions have been granted for allow.resource(createAccount).to(["manageGroups", "addUserToGroup", "manageGroupMembership"]) as well as modifying DynamoDB data. However as soon as either CognitoIdentityProviderClient or await client.models.User.create(user) are hit, I get the following error from Graphql API No federated jwt. Example of code used:

const user = {
  userId: userId,
  ...
};
const { data, errors} = await client.models.User.create(user);   <-- `No federated jwt` error thrown here

Or

const cognitoClient = new CognitoIdentityProviderClient();
const userGroup = {
  GroupName: `GroupName`,
  Precedence: 1,
  Description: `Description`,
  UserPoolId: userPoolId,
};
const createCommand = new CreateGroupCommand(userGroup);
const response = await cognitoClient.send(createCommand );    <-- `No federated jwt` error thrown here

The examples in the Amplify Gen 2 documentation don't cover this scenario. What am I missing?

1 Answer
0
Accepted Answer

Cognito issue: Use the following package which uses the IAM credentials that the function has:

const cognito = new AWS.CognitoIdentityServiceProvider();

const readGroup = {
    Description: `Read group for ${clientName}`,
    GroupName: `Read-${clientAccountId}`,
    Precedence: 2,
    UserPoolId: userPoolId,
  };

const newGroup: AWS.CognitoIdentityServiceProvider.CreateGroupResponse | undefined = await new Promise((resolve, reject) => {
   return cognito.createGroup(readGroup, function (err, data) {
    if (err) {
      throw err;
    } else {
      resolve(data);
    }
  });
});

Graphql / DynamoDB issue: Add the JWT token from the request as a param of the create request:

const authToken = event.request.headers['authorization'] ?? '';

const user = {
  userId: userId,
  ...
};

const { data: updatedUser, errors: userCreateErrors } = await client.models.User.create(
  user,
  {
    authMode: 'identityPool',
    authToken: authToken
  }
);
Jonny
answered a month ago