How to add Facebook authentication to a serverless API
In this example we will look at how to add Facebook authentication to a serverless API using SST.
Requirements
- Node.js 16 or later
- We’ll be using TypeScript
- An AWS account with the AWS CLI configured locally
- A Facebook app
Create an SST app
Let’s start by creating an SST app.
$ npx create-sst@latest --template=base/example api-auth-facebook
$ cd api-auth-facebook
$ npm install
By default, our app will be deployed to an environment (or stage) called dev
and the us-east-1
AWS region. This can be changed in the sst.config.ts
in your project root.
import { SSTConfig } from "sst";
import { Api } from "sst/constructs";
export default {
config(_input) {
return {
name: "api-auth-facebook",
region: "us-east-1",
};
},
} satisfies SSTConfig;
Project layout
An SST app is made up of two parts.
-
stacks/
— App InfrastructureThe code that describes the infrastructure of your serverless app is placed in the
stacks/
directory of your project. SST uses AWS CDK, to create the infrastructure. -
packages/
— App CodeThe code that’s run when your API is invoked is placed in the
packages/
directory of your project.
Setting up the API
Let’s start by setting up an API.
Replace the stacks/ExampleStack.ts
with the following.
import { Api, Cognito, StackContext } from "sst/constructs";
export function ExampleStack({ stack }: StackContext) {
// Create Api
const api = new Api(stack, "Api", {
defaults: {
authorizer: "iam",
},
routes: {
"GET /private": "functions/private.handler",
"GET /public": {
function: "functions/public.handler",
authorizer: "none",
},
},
});
// Show the API endpoint and other info in the output
stack.addOutputs({
ApiEndpoint: api.url,
});
}
We are creating an API here using the Api
construct. And we are adding two routes to it.
GET /private
GET /public
To secure our APIs we are adding the authorization type AWS_IAM
. This means the caller of the API needs to have the right permissions. The first route is a private endpoint. The second is a public endpoint and its authorization type is overriden to NONE
.
Setting up authentication
Now let’s add authentication for our serverless app.
Add this below the Api
definition in stacks/ExampleStack.ts
. Make sure to replace the appId
with that of your Facebook app.
// Create auth provider
const auth = new Cognito(stack, "Auth", {
identityPoolFederation: {
facebook: { appId: "419718329085014" },
},
});
// Allow authenticated users invoke API
auth.attachPermissionsForAuthUsers(stack, [api]);
This creates a Cognito Identity Pool which relies on Facebook to authenticate users. And we use the attachPermissionsForAuthUsers
method to allow our logged in users to access our API.
Replace the stack.addOutputs
call with the following.
stack.addOutputs({
ApiEndpoint: api.url,
IdentityPoolId: auth.cognitoIdentityPoolId,
});
We are going to print out the resources that we created for reference.
Adding function code
Let’s create two functions, one handling the public route, and the other for the private route.
Add a packages/functions/src/public.ts
.
export async function handler() {
return {
statusCode: 200,
body: "Hello stranger!",
};
}
Add a packages/functions/src/private.ts
.
export async function handler() {
return {
statusCode: 200,
body: "Hello user!",
};
}
Now let’s test our new API.
Starting your dev environment
SST features a Live Lambda Development environment that allows you to work on your serverless apps live.
$ npm start
The first time you run this command it’ll take a couple of minutes to do the following:
- It’ll bootstrap your AWS environment to use CDK.
- Deploy a debug stack to power the Live Lambda Development environment.
- Deploy your app, but replace the functions in the
packages/
directory with ones that connect to your local client. - Start up a local client.
Once complete, you should see something like this.
===============
Deploying app
===============
Preparing your SST app
Transpiling source
Linting source
Deploying stacks
dev-api-auth-facebook-ExampleStack: deploying...
✅ dev-api-auth-facebook-ExampleStack
Stack dev-api-auth-facebook-ExampleStack
Status: deployed
Outputs:
ApiEndpoint: https://2zy74sn6we.execute-api.us-east-1.amazonaws.com
IdentityPoolId: us-east-1:84340cf1-4f64-496e-87c2-517072e7d5d9
The ApiEndpoint
is the API we just created. Make a note of the IdentityPoolId
, we’ll need that later.
Now let’s try out our public route. Head over to the following in your browser. Make sure to replace the URL with your API.
https://2zy74sn6we.execute-api.us-east-1.amazonaws.com/public
You should see the greeting Hello stranger!
.
And if you try to visit the private route, you will see {"message":"Forbidden"}
.
https://2zy74sn6we.execute-api.us-east-1.amazonaws.com/private
Login with Facebook
We are going to use Facebook’s Graph API explorer to test logging in with Facebook. Head over to — developers.facebook.com/tools/explorer
Select your Facebook App and select Generate Access Token. Copy the generated access token.
Next, we need to get the user’s Cognito Identity id. Replace --identity-pool-id
with the IdentityPoolId
from the sst dev
log output; and replace the --logins
with the Access Token from the previous step.
$ aws cognito-identity get-id \
--identity-pool-id us-east-1:84340cf1-4f64-496e-87c2-517072e7d5d9 \
--logins graph.facebook.com="EAAF9u0npLFUBAGv7SlHXIMigP0nZBF2LxZA5ZCe3NqZB6Wc6xbWxwHqn64T5QLEsjOZAFhZCLJj1yIsDLPCc9L3TRWZC3SvKf2D1vEZC3FISPWENQ9S5BZA94zxtn6HWQFD8QLMvjt83qOGHeQKZAAtJRgHeuzmd2oGn3jbZBmfYl2rhg3dpEnFhkAmK3lC7BZAEyc0ZD"
You should get an identity id for the Facebook user.
{
"IdentityId": "us-east-1:46625265-9c97-420f-a826-15dbc812a008"
}
Now we’ll need to get the IAM credentials for the identity user.
$ aws cognito-identity get-credentials-for-identity \
--identity-id us-east-1:46625265-9c97-420f-a826-15dbc812a008 \
--logins graph.facebook.com="EAAF9u0npLFUBAGv7SlHXIMigP0nZBF2LxZA5ZCe3NqZB6Wc6xbWxwHqn64T5QLEsjOZAFhZCLJj1yIsDLPCc9L3TRWZC3SvKf2D1vEZC3FISPWENQ9S5BZA94zxtn6HWQFD8QLMvjt83qOGHeQKZAAtJRgHeuzmd2oGn3jbZBmfYl2rhg3dpEnFhkAmK3lC7BZAEyc0ZD"
You should get a set of temporary IAM credentials.
{
"IdentityId": "us-east-1:46625265-9c97-420f-a826-15dbc812a008",
"Credentials": {
"AccessKeyId": "ASIARUIS6Q2MOT2D7LGE",
"SecretKey": "r9xMZBe7KXqKYUTBPuGR8jziNrkD8XpL5g2r9Pgw",
"SessionToken": "IQoJb3JpZ2luX2VjEHYaCXVzLWVhc3QtMSJHMEUCIA/0ccZZvhjSPnoXkzJ/TUiSPXB2ON/1Qnn2/omfQOQLAiEA+qjuBHYwZvHG8Q9cfjd/0yloUkh5pkEUzEiCjjaa5FYq6QMIbhACGgwxMTIyNDU3Njk4ODAiDGDpiBCuNOBhkktiHyrGA7A8scWUjxzwUKaEAzYdWOwxDdYxA21wPc3Bz2NSJlscwHQP0AjmZ3aPmEREgwhi92/5SGETFINbJSRDs9dsJ+hrArHpSyoOp6UmXX/48q8b9BbWKB2qeF/kIPMG+1urwgTLn7I9cmYNH0LUHLJ0/EaRVxFo/hUTnTiPsDZCD9X96WxvO+cfjhmpAdCTR8MjxUl4k18grIWzPBkNAJwS1D+zIuoQTQPiIN6e25pWi3Mi+wXxgz+ToBFiPeybl3Q9qHOH0gQipss5eYrMFYaRWS3k6eOLCZoTOA4T/sMoJMweGwT2V33C1/o95W0LXCwYuAWg9bdUC71DHtc9bPY1NCAWqQcnxQabziZkOFTW5aLeDsY53TDPFoYiQ8lUrmDLhZSU3MsBcXVtPsvI5MPmoIqyf62ccd8VJo7idS5yyobZz9Ku7/jG/ZmU5S0jdpjWIVqBGNd5aG4R6Vf41FqMN0bEcz2qQBRFTeRg+UDQTv6Hc0kM943iXXBNdzVptivlkEV/fN5NN8sC5zXOafWUMJ8raQhPOAvWTVPIo8aXfAlKzcAqA/8bzJOzeEADcW71XGABOSzhy5TQayqWVrIX8ksBWMmFcSMwqJSDgQY6hAINr+bYzf+Vp1knGBWE52ArJAWzcss9UQU+b0kXripIvFpbdSCn3Yz4+kHKmmgvLKCEGo2k+zJW8TP+j+f3PsQinCB1VHpLpL2G+rx4aK/wMZ48ALY/rIK8KcYArnmjga5IT/PC/4cRW0z1vCucGQibKZ5skF0tUnpLb3BNwGP42NrtoaFkHPmihRpvvpS93iHX8HavIkpEzNcgkKzCcL3tdWXlnN9Hx/CI1kpb4ubzYaAQYiuURYKrFySzkaAJAvSkCO0ZjG342YHe9V+WEC/VBDRJllSiPBAnWaWrDsymafAKUA3HylrvKAetXaK8sSwGQ3DfkJ6GedJTel3FDN8jzZOo9A==",
"Expiration": "2021-02-08T01:20:40-05:00"
}
}
Let’s make a call to the private route using the credentials. The API request needs to be signed with AWS SigV4. We are going to use Insomnia to help us sign and make this request.
Make sure to replace the Access Key Id, Secret Access Key, Region, and Session Token below. In our case the region is us-east-1
. You can see this in the API URL.
https://2zy74sn6we.execute-api.us-east-1.amazonaws.com
You should now see.
Hello user!
The above process might seem fairly tedious. But once we integrate it into our frontend app, we’ll be able to use something like AWS Amplify to handle these steps for us.
Making changes
Let’s make a quick change to our private route and print out the caller’s user id.
Replace packages/functions/src/private.ts
with the following.
import { APIGatewayProxyHandlerV2 } from "aws-lambda";
export const handler: APIGatewayProxyHandlerV2 = async (event) => {
return {
statusCode: 200,
body: `Hello ${event.requestContext.authorizer.iam.cognitoIdentity.identityId}!`,
};
};
We are getting the user id from the event object.
If you head back to Insomnia and hit the /private
endpoint again.
You should see the user id. Note, this matches the identity id that was generated from the step where we generated a set of IAM credentials.
Hello us-east-1:46625265-9c97-420f-a826-15dbc812a008!
Deploying your API
Now that our API is tested and ready to go. Let’s go ahead and deploy it for our users. You’ll recall that we were using a dev
environment, the one specified in your sst.config.ts
.
However, we are going to deploy your API again. But to a different environment, called prod
. This allows us to separate our environments, so when we are working in dev
, it doesn’t break the API for our users.
Run the following in your terminal.
$ npx sst deploy --stage prod
A note on these environments. SST is simply deploying the same app twice using two different stage
names. It prefixes the resources with the stage names to ensure that they don’t thrash.
Cleaning up
Finally, you can remove the resources created in this example using the following command.
$ npx sst remove
And to remove the prod environment.
$ npx sst remove --stage prod
Conclusion
And that’s it! You’ve got a brand new serverless API authenticated with Facebook. A local development environment, to test and make changes. And it’s deployed to production as well, so you can share it with your users. Check out the repo below for the code we used in this example. And leave a comment if you have any questions!
Example repo for reference
github.com/serverless-stack/sst/tree/master/examples/api-auth-facebookFor help and discussion
Comments on this exampleMore Examples
APIs
-
REST API
Building a simple REST API.
-
WebSocket API
Building a simple WebSocket API.
-
Go REST API
Building a REST API with Golang.
-
Custom Domains
Using a custom domain in an API.
Web Apps
-
React.js
Full-stack React app with a serverless API.
-
Next.js
Full-stack Next.js app with DynamoDB.
-
Vue.js
Full-stack Vue.js app with a serverless API.
-
Svelte
Full-stack Svelte app with a serverless API.
-
Gatsby
Full-stack Gatsby app with a serverless API.
-
Angular
Full-stack Angular app with a serverless API.
Mobile Apps
GraphQL
Databases
-
DynamoDB
Using DynamoDB in a serverless API.
-
MongoDB Atlas
Using MongoDB Atlas in a serverless API.
-
PostgreSQL
Using PostgreSQL and Aurora in a serverless API.
-
CRUD DynamoDB
Building a CRUD API with DynamoDB.
-
PlanetScale
Using PlanetScale in a serverless API.
Authentication
Using SST Auth
-
Facebook Auth
Adding Facebook auth to a full-stack serverless app.
-
Google Auth
Adding Google auth to a full-stack serverless app.
Using Cognito Identity Pools
-
Cognito IAM
Authenticating with Cognito User Pool and Identity Pool.
-
Twitter Auth
Authenticating a serverless API with Twitter.
-
Auth0 IAM
Authenticating a serverless API with Auth0.
Using Cognito User Pools
-
Cognito JWT
Adding JWT authentication with Cognito.
-
Auth0 JWT
Adding JWT authentication with Auth0.
-
Google Auth
Authenticating a full-stack serverless app with Google.
-
GitHub Auth
Authenticating a full-stack serverless app with GitHub.
-
Facebook Auth
Authenticating a full-stack serverless app with Facebook.
Async Tasks
-
Cron
A simple serverless Cron job.
-
Queues
A simple queue system with SQS.
-
Pub/Sub
A simple pub/sub system with SNS.
-
Resize Images
Automatically resize images uploaded to S3.
-
Kinesis data streams
A simple Kinesis Data Stream system.
-
EventBus
A simple EventBridge system with EventBus.
Editors
-
Debug With VS Code
Using VS Code to debug serverless apps.
-
Debug With WebStorm
Using WebStorm to debug serverless apps.
-
Debug With IntelliJ
Using IntelliJ IDEA to debug serverless apps.
Monitoring
Miscellaneous
-
Lambda Layers
Using the chrome-aws-lambda layer to take screenshots.
-
Middy Validator
Use Middy to validate API request and responses.