Introduction
On this part, we are going to join the authentication, backend, and frontend elements to create a safe Single Web page Software (SPA) utilizing a CloudFormation (CFN) template. Whereas the template is not good, it is near being production-ready. Determine 1 illustrates how all of the elements come collectively.
Determine 1: All of the elements linked
Let’s briefly evaluation what we have lined within the earlier elements and the modifications wanted to combine them:
-
Half 1 : Idea. No modifications
-
Half 2 : Frontend setup, together with the deployment of an AWS CloudFront CDN Distribution. On this half, we’ll replace its CFN template to route frontend
/api
queries to the backend. -
Half 3 : Backend setup, configuring a VM (EC2 Occasion) to run the REST API Server and an API Gateway to proxy requests to the VM. On this half, we’ll additionally make modifications to guard the API Gateway utilizing our OpenID Server JSON Internet Token (JWT). We’ll additionally change the backend endpoint from
/greeting
to/api/greeting
. -
Half 4 : Id Supplier, the place we deployed AWS Cognito because the OpenID Server for person authentication. No modifications are wanted on this half for the preliminary CFN template.
Supply code repository
javatask/aws-spa-beginners-guide: Code for the blog series on porting single page application to AWS (github.com)
Join Frontend to the Backend
To attach the frontend and backend, we’ll make modifications to the frontend.yml
file. Yow will discover the complete CFN template within the repository.
AssetsDistribution:
Sort: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
...
- Id: APIBackend
DomainName: !Ref APIEndpoint
OriginPath: !Sub "/${APIEndpointStage}"
CustomOriginConfig:
OriginProtocolPolicy: https-only
...
CacheBehaviors:
- PathPattern: "/api/*"
AllowedMethods:
- GET
- POST
- PATCH
- PUT
- DELETE
- HEAD
- OPTIONS
TargetOriginId: APIBackend
CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad # CachingDisabled
OriginRequestPolicyId: b689b0a8-53d0-40ab-baf2-68738e2966ac # AllViewerExceptHostHeader
ResponseHeadersPolicyId: 67f7725c-6f97-4210-82d7-5512b31e9d03 # SecurityHeadersPolicy
ViewerProtocolPolicy: redirect-to-https
....
These modifications are targeted on including a brand new origin and mapping /api
to the brand new origin.
After making these updates, let’s replace the prevailing Frontend stack with the brand new CFN template:
aws cloudformation update-stack --stack-name your-unique-stack-name --template-body file://frontend.yaml
--parameters ParameterKey=APIEndpoint,ParameterValue=xxxxxxx.execute-api.eu-central-1.amazonaws.com
After the profitable replace, strive reaching the /api
endpoint utilizing the CloudFront URL:
curl https://xxxxxxxxxx.cloudfront.internet/api/greeting
You must obtain a profitable response:
{"id":8,"content material":"Whats up, World!"}
Congratulations! You could have efficiently linked the Frontend and Backend.
Nonetheless, your backend is presently susceptible, missing an authentication layer.
Defending Backend with Id Supplier (Cognito)
On this part, we’ll combine AWS Cognito with API Gateway to guard the backend. The principle aim is to reject all requests besides these with an Authorization Header containing a JWT issued by AWS Cognito.
To realize this aim, I made modifications to the backend.yaml
:
Sources:
...
ApiGatewayAuthorizer:
Sort: AWS::ApiGateway::Authorizer
Properties:
Title: !Sub ${AWS::StackName}-authorizer-backend-proxy
Sort: COGNITO_USER_POOLS
IdentitySource: methodology.request.header.Authorization
RestApiId: !Ref ApiGatewayRestApi
ProviderARNs:
- !Ref CognitoPoolArn
...
ApiGatewayMethod:
Sort: AWS::ApiGateway::Methodology
Properties:
...
AuthorizationType: COGNITO_USER_POOLS
AuthorizerId: !GetAtt ApiGatewayAuthorizer.AuthorizerId
Let’s break down what these modifications do:
-
ApiGatewayAuthorizer : On this part, we outline an authorizer for the Amazon API Gateway. An authorizer controls entry to your API strategies.
-
ApiGatewayMethod : Right here, we outline a technique for the API Gateway.
In abstract, this CloudFormation script defines an API Gateway methodology that makes use of a Cognito person pool for authorization. Customers making an attempt to name this API methodology should current a sound token from the corresponding Cognito person pool within the Authorization header of their request.
To deploy these updates, run the next command:
aws cloudformation deploy
--stack-name one-click-backend
--template-file backend.yaml
--parameter-overrides CognitoPoolArn=$cognitoPoolArn ContainerURI=$containerUrl
--capabilities CAPABILITY_IAM
Testing the Closing Product
Use your CloudFront URL to entry the web site a part of your software. You must see “Login” and “Fetch Knowledge” buttons.
Open the developer console and click on “Fetch knowledge.” You must obtain an error, as a result of JWT shouldn’t be discovered.
Now, click on “login” and undergo the login course of. A profitable login ought to lead to lots of knowledge being printed to your console, it is your JWT.
The id_token
is the worth that will likely be used to question our protected backend.
Click on “Fetch knowledge” yet one more time, and it’s best to obtain knowledge out of your backend in your HTML web page: {“id”:9,”content material”:”Whats up, World!”}
Nicely carried out! We’re nearly prepared with all of the elements for a production-ready CFN template.
Abstract
On this article, we demonstrated easy methods to securely join authentication, backend, and frontend elements utilizing a CloudFormation template for a Single Web page Software (SPA). We lined updates to the Frontend and Backend templates, the combination of AWS Cognito with API Gateway for authorization, and testing the ultimate product. By the tip of this tutorial, it’s best to have a safe and almost production-ready SPA setup.
Within the subsequent half, we’ll current your ultimate script that may carry out a “one-click” deployment of our software.