Secure Your Static Website with AWS CloudFront and Lambda

Photo by Aubrey Odom on Unsplash

TL;DR

High-Level Diagram

Creating a Single Page Application

# create-react-app aws-react-jwt-auth
Navigation between public and protected components
import asyncComponent from "./AsyncComponent";
import {withAuthenticator} from 'aws-amplify-react';

const AsyncProtected = asyncComponent(() => import("./Protected"));

class App extends Component {
render() {
return (
...
<Route path="/protected" component={AsyncProtected}/>
...
);
}
}
const AsyncProtected = asyncComponent(() => import(/* webpackChunkName: "protected/a" */ "./Protected"));
Loading protected components separately
Cognito configuration
npm i aws-amplify aws-amplify-react
<Route path="/protected" component={withAuthenticator(AsyncProtected)}/>
Adding authentication with AWS Cognito and Amplify to you App

Creating CloudFront Distribution

Creating Lambda@Edge function to Authorize access

exports.handler = (event, context, callback) => {
const cfrequest = event.Records[0].cf.request;
if (!cfrequest.uri.startsWith("/static/js/protected")) {
callback(null, cfrequest);
return true;
}
...
}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"edgelambda.amazonaws.com",
"lambda.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}
Pick the right CloudFront distribution in the deployment dialog
A protected chunk of JS is now secured on the backend

Let’s Test It

End-to-end test

👏

Final Notes and Considerations

--

--

--

Engineering Lead @ Square, Co-Founder of Sygn — on a journey to create a frustration-free payment experience

Love podcasts or audiobooks? Learn on the go with our new app.

7 JavaScript data structures you must know

Evmos Guardians Mint Guide! June 23rd

React state={}

Traditional Tool To Use Windows Based GUI During Automation

Learning React with Ben Awad — 08

Wax on, Wax off#404

How to create a logical OR query in Cloud Firestore with the JavaScript SDK?

Batch Download Assets from Zeplin

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vasilii Trofimchuk

Vasilii Trofimchuk

Engineering Lead @ Square, Co-Founder of Sygn — on a journey to create a frustration-free payment experience

More from Medium

Google Login on AWS Cognito Without Hosted UI (Work-around)

Authentication Using Amazon Cognito Hosted UI for Simple React Application (Part 1)

How to find API gateway URLs

How to set up an AWS Route 53 custom domain for your Heroku app