Implementing JavaScript for User Access Control
To address this issue, a simple solution is to load the dashboard.html page and include JavaScript within the body of dashboard.html to manage content visibility based on whether the user is logged in or not (e.g., by checking for a Cognito JWT token in LocalStorage) and redirect unauthenticated users to login.html.
Note: This method can also be beneficial if you intend to utilize AWS Cognito UserPools Hosted UI.
Controlling Access
If the goal is to restrict access to dashboard.html, CloudFront Signed Cookies can be utilized as outlined below.
- Configure S3 access via AWS CloudFront (establishing an Origin Access Identity - OAI) and set the S3 buckets to private (for all three pages). Link the OAI with the S3 origins using the wizard.
- Create separate behaviors for each html file.
- For the login.html and register.html behaviors, maintain Restrict Viewer Access(Use Signed URLs or Signed Cookies) as No
- For dashboard.html specifically, set Restrict Viewer Access(Use Signed URLs or
Signed Cookies) to Yes
- If a user attempts to directly access dashboard.html (without logging in), CloudFront will generate an error. Therefore, configure the AWS CloudFront error response to direct to Login.html.
- Develop an API Gateway and Lambda endpoint to validate the Cognito JWT Token from the Login Page, generating a Signed Cookie in Lambda and transmitting it in the setCookie header.
- The browser will send the Cookie header, allowing CloudFront to permit loading of dashboard.html when the Cookie is present.