Invoke API Gateway function with Cognito Authentication from Javascript

I created some functions with Serverless framework and now I have some API Gateway endpoints.
I created a static S3 JS page and I’m calling these endpoints and it’s working fine!
Now I want to add Cognito Authentication to these endpoints.
I already added Facebook login to the frontend and I’m using this login to authenticate on a Federated Pool on Cognito and it’s also working fine.
The missing piece I don’t find is what to do next to use this authentication to ask something on my serverless services.

Thanks!

Have you seen the authorizers documentation? I haven’t done it myself yet, but there’s a section in there detailing the use of Cognito User Pools.

Yes,I’ve seen it. Thanks anyway.
But this only explains how to configure it on the service itself, what I don’t know yet is how do I call one of these functions on the frontend with authentication.
Right now I’m simply doing an Ajax call via Javascript to these functions without any headers.
For what I’ve read until now I think I need to use Api Gateway SDK but I don’t know if I could do the same by just passing some information on the headers of the Ajax call.

1 Like

@dbeja Are you using the User Pool + Identity Pool setup? Or just Identify Pool?

If you are using Identity Pool federated with Facebook login, you might find this stackoverflow answer useful amazon web services - How to authenticate API Gateway calls with Facebook? - Stack Overflow

To use a federated identity, you set the API Gateway method to use “AWS_IAM” authorization. You use Cognito to create a role and associate it with your Cognito identity pool. You then use the Identity and Access Management (IAM) service to grant this role permission to call your API Gateway method.

And then use aws sdk in JS to invoke the apis

var apigateway = new AWS.APIGateway();

If you are using User Pool, you can authenticate your apis with the User Pool and include the Authentication header in your Ajax call. See the code here Call the Create API

1 Like

Thanks fanjie!

I’m using just a Identity Pool federated with Facebook login.

I just need to use AWS SDK Javascript or do I need to download also API Gateway SDK Javascript?

Right now I have this callback:

AWS.config.credentials.get(function(err){
console.log(err);
});

Where the user is authenticate on Cognito, but I can’t find any example on what to do next, how does AWS.APIGateway knows it’s authenticated and how do I call the functions with this apigateway. Do you know any examples I could follow? The ones I found seem to be a different case scenario.

Thank you!

2 Likes

@dbeja You probably have it figured out already.

I played around with social login + cognito, and it seems you could just use the JS SDK generated from the API Gateway console.

And here are the instructions on using it. Ignore step 6 and 7 since the AWS credentials are already set after the AWS.config.credentials.get() call.

1 Like