Protect website with Cognito

Previous post we demonstrated how distributing and securely deploying the website to global end users. The authentication and authorization are always mandatory features of web application. Amazon Cognito is a managed AWS serverless service helping the applications to implement AuthN and AuthZ, with Cognito the applications securely scales to millions of users(up to 50,000 free users) supporting identity and access management standards, such as OAuth 2.0, SAML 2.0, and OpenID Connect.

The web application uses AWS Amplify to integrate with AWS services, such as Cognito and API Gateway. Below the procedures how integrating Cognito as AuthN via Amplify in Todolist project,

  1. add amplify JS libraries into your project's dependencies
 1{
 2  "name": "todo-list",
 3  "dependencies": {
 4    "@aws-amplify/ui-react": "^3.5.0",
 5    "aws-amplify": "^4.3.34",
 6    "axios": "^0.27.2",
 7    "react": "^18.2.0",
 8    "react-dom": "^18.2.0",
 9    "react-icons": "^4.4.0",
10    "sweetalert2": "^11.4.24",
11    "uuid": "^8.3.2"
12  }
13}
  1. load the configuration file from server side and configure the Amplify categories
 1  useEffect(() => {
 2    setLoadingConfig(true);
 3    Axios.get("/aws-exports.json").then((res) => {
 4      const configData = res.data;
 5      const tokenHeader = async () => { return { Authorization: `Bearer ${(await Auth.currentSession()).getIdToken().getJwtToken()}` }; };
 6      configData.API.endpoints[0].custom_header = tokenHeader;
 7      Amplify.configure(configData);
 8      apiEndpointName = configData.API.endpoints[0].name;
 9      setApiEndpoint(configData.API.endpoints[0].name);
10      
11      Hub.listen('auth', ({ payload }) => {
12        const { event } = payload;
13        switch (event) {
14          case 'signIn':
15          case 'signUp':
16          case 'autoSignIn':
17            getTasks();
18            break;
19        }
20      });
21      
22      getTasks();
23      
24      setLoadingConfig(false);
25    });
26  }, []);
  1. use [Authenticator component][authenticator] adding complete authentication flows with minimal boilerplate
 1  return (
 2    <Authenticator components={components} loginMechanisms={['email']}>
 3      {({ signOut, user }) => (
 4        <Flex
 5          direction="column"
 6          justifyContent="flex-start"
 7          alignItems="center"
 8          alignContent="flex-start"
 9          wrap="nowrap"
10          gap="1rem"
11          textAlign="center"
12        >
13          <View width="100%">
14            ...
15          </View>
16        </Flex>
17      )}
18    </Authenticator>    
19  )
  1. update TODO CRUD methods to use Amplify's API catagory to make HTTP requests to API Gateway
 1  const getTasks = async () => {
 2    const canEnter = await ionViewCanEnter();
 3    if (canEnter) {
 4      try {
 5        setLoadingData(true);
 6        
 7        const initData = {
 8          headers: { "content-type": "application/json" }, // OPTIONAL
 9          response: true, // OPTIONAL (return the entire Axios response object instead of only response.data)
10        };        
11        API
12        .get(apiEndpointName || apiEndpoint, "/todo", initData)
13        .then(res => {
14          setLoadingData(false);
15          const tasksData = res.data;
16          if ((typeof tasksData === "string")) {
17            Swal.fire("Ops..", tasksData);
18          } else {
19            setTasks(tasksData);
20          }
21        })
22        .catch(error => {
23          setLoadingData(false);
24          console.error(error);
25          Swal.fire(
26            `${error.message}`,
27            `${error?.response?.data?.message}`,
28            undefined
29          );
30        });
31      } catch (error) {
32        console.info(error);
33      }
34    }
35  };

All above changes are implemented Cognito authN with the web react application.

In the server-side the Cognito user pool will be provisioned, the API Gateway endpoint is authorized by Cognito user pool authorizer. The Amplify configuration file aws-exports.json will be created on the air when provisioning the stack with the user pool and API information.

As usual, all AWS resources are orchestrated by AWS CDK project, it's easliy to be deployed to any account and any region of AWS!

Happying protecting the website with Cognito 🔒 😆😆😆

Posts in this Series