In this exercise, you will add a sign-up/sign-in component to your application by using Amazon Cognito. After setting up Amazon Cognito, the photos will get stored to/retrieved from the user created in Amazon Cognito.
Note: Make sure to sign in to your AWS account with the AWS IAM user edXProjectUser credentials.
To begin, follow the steps below.
1. Start the RDS database instance.
- In the AWS Console, click Services, then click Relational Database Service to open the Amazon RDS dashboard.
- In the left navigation pane, click Instances. From the list of instances, select edx-photos-db.
- At the top, click Instance actions, and then click Start.
2. Set up an Amazon Cognito user pool.
- In the AWS Console, go to the Amazon Cognito
- Make sure you are still in the Oregon (us-west-2) region.
- Click Manage your User Pools.
- At the top right corner, click Create a user pool.
- For Pool name, type photos-pool.
- Click Step through settings.
- For How do you want your end users to sign in?, select Email address or phone number.
- For Which standard attributes do you want to require?, select Nickname.
- Click Next step.
- Leave the default settings on the Policy page and click Next step.
- Skip the MFA and verifications pages and click Next step.
- On the Message customization page, select Verification Type as Link. Feel free to customize the email body.
- Click Next Step.
- Skip the Tag section and click Next Step.
- Leave the default setting on the Devices page and click Next step.
- On the App Clients page, click Add an app client.
- For App client name, type a client name, for example, WebsiteClient.
- Leave the other default settings and click Create app client.
- Click Next Step.
- Skip the Triggers page and click Next Step
- On the Review page, click Create Pool.
- After the pool is created, write down the Pool ID for later use.
- In the left navigation menu, under App integration, click App client settings.
- For Enabled Identity Providers, check Cognito User Pool.
- For Callback URL(s), type http://localhost:5000/callback
- For Sign out URL(s), type http://localhost:5000/
- Under OAuth 2.0, for Allowed OAuth Flows, select Authorization code grant and for Allowed OAuth Scopes, select openid.
- Click Save changes at the bottom.
- In the left navigation menu, under App integration, click Domain name.
- Type a domain name, check its availability, and click Save changes. Write down the domain name for later use.
- In the left navigation menu, under General settings, click App clients.
- Click Show details.
- Make a note of the App client ID and App client secret for later use.
- Click Return to pool details at the bottom to return to the Pool details page.
3. Download and explore the exercise code.
- Type the command below in your AWS Cloud9 terminal to make sure you are in the ~/environment directory of your AWS Cloud9 instance.
cd ~/environment
- In your AWS Cloud9 environment, download the exercise code by typing the command below in the terminal.
wget https://us-west-2-tcdev.s3.amazonaws.com/courses/AWS-100-ADG/v1.0.0/exercises/ex-cognito.zip
- Unzip the exercise code .zip file by typing the command below in your AWS Cloud9 terminal.
unzip ex-cognito.zip
The contents of the .zip file should be extracted to a folder with a similar name. You can view the folder on the left tree view.
- Open the exercise-cognito/FlaskApp/application.py file. Scroll through the contents and find the routes for /login, /logout, and /callback. Notice that the Amazon Cognito settings are being pulled from the config file, config.py. You may explore the code by referring to the commented documentation links in each of the routes.
4. Configure the Amazon Cognito environment variables and run the exercise code.
- In your AWS Cloud9 environment, open the exercise-cognito/FlaskApp/config.py file.
- You should now see the environment variables COGNITO_POOL_ID, COGNITO_CLIENT_ID, COGNITO_CLIENT_SECRET, COGNITO_DOMAIN, and BASE_URL in the list of environment variables.
- In your AWS Cloud9 environment, on the Python3RunConfiguration pane at the bottom, click ENV on the right side. You should see a small list showing the previously configured environment variables.
- To configure the Amazon Cognito environment variables, type the environment variable Name and Value as shown in the table below:
COGNITO_POOL_ID |
Copy and paste the pool ID you noted earlier. |
COGNITO_CLIENT_ID |
Copy and paste the App Client ID you noted earlier. |
COGNITO_CLIENT_SECRET |
Copy and paste the App Client Secret you noted earlier. |
COGNITO_DOMAIN |
Copy and paste the domain name you created earlier. It should look similar to the example below. Do not copy the entire URL starting with https://.
YOUR_DOMAIN_NAME.auth.us-west-2.amazoncognito.com |
BASE_URL |
http://localhost:5000
Do not include a trailing / for the BASE_URL. |
Note: Make sure to delete any white space that was inserted while copy/pasting.
- To run the exercise code, you will need to point the Run Configuration to the correct exercise folder. On the Python3RunConfiguration pane at the bottom, type the text shown below in the Command text box and click Run.
exercise-cognito/FlaskApp/application.py
You should see a message like the one below:
Running on http://0.0.0.0:5000/
5. Establish an SSH tunnel to your AWS Cloud9 instance.
To test the application, you will need to establish an SSH tunnel to your AWS Cloud9 instance.
For MAC/Linux users:
- In your MAC/Linux terminal, type the command below to get the public portion from your existing key pair .pem file. Make sure to replace YOUR_KEY with the name of the key pair .pem file you created in the third exercise.
ssh-keygen -f YOUR_KEY.pem -y
- The output looks like the example below. Copy the output of your command.
ssh-rsa
AAAAB3NzaC1yc2EAAAADAQABAAABAQDWGRZsPraV6v4UqfZTFKAXK9bhjWVkONEKyAA1CeOkxSN+9WdY7gKgjbPOeUx3LFqRudBvSrP+eKTtthPrl Nx9UBvXniVK252i4h0xnIcrRO1PUpq0EzyqX+n3u2YwytT+on6x98PRjtD4oCKyfFviWBqnRHtWvRre8CWhULuJrmUeo2aPrVTPXo/TwJpZupXv63YyUMPC 2wyDMDsKNZhsqUedkJ8575PGXCg9gEkPg2ulR8NUrzDSfbXIrZLgCcIziwDQ0dA9B28OAQ9saPyXYzrZF1ZmCxKgzSHHiKdBAJ0E/X/s53N5Hg04SIWy4D4lMT 9g+AZG38YPNq68mo4b
- In your AWS Cloud9 instance, on the left pane, click the Settings icon. Click Show Home in Favorites and Show Hidden Files as shown in the screenshot below.
This should display the .ssh folder in the tree view.
- Expand the .ssh folder and open the authorized_keys file.
- Paste the public key you copied earlier in the authorized_keys file.
- Save the authorized_keys file. By updating this file, you are telling your AWS Cloud9 instance to allow connections that authenticate with the matching private key.
- Write down the public IP address of your AWS Cloud9 instance.
- In your MAC terminal, type the command below. Replace CLOUD9-PUBLIC-IP with the public IP address of the AWS Cloud9 instance. Replace YOUR_KEY.pem with your .pem file.
ssh -i YOUR_KEY.pem ec2-user@CLOUD9-PUBLIC-IP -L 5000:localhost:5000
You have now established an SSH tunnel to your AWS Cloud9 instance.
For Windows users:
- Open the PuTTYgen application. PuTTYgen is automatically installed when you install PuTTY.
- Click Load, then locate and open the private key pair you created in the third exercise. Upon loading, you should see a public key like the one below.
ssh-rsa
AAAAB3NzaC1yc2EAAAADAQABAAABAQCwvZG4maQlnb0A0Pl5bwfU8nVtzqb4VgC06bKlLtVxdBCNqDWaJDk2hd6Od/c3kByR/PgcR7YHX6rVi44RVg5Gh+rKeJP7 odcrWBXY0DhTSvdDDG2iN39kfvfGfWqZCSmhEcqpXlyLi0jaisD1YND4qN0dqtCbjdnrqRoqpabRaYnpkgK/1qqUPzJgWVhBX++ByWl2Rvb3gFd/nJEE+oR3fupw 06/hB1vj9pcX52G2JhEFZQR5z4xbwj+Nm4SusockYQ+FYrno50ATrfoTQU5Zf9VrWnQbG9Z6Mh2pzjLhhvx+AtChbOllzuvxfTf3fKQbxph7p3QEfXOAzcQ/4FxX imported-openssh-key
- Copy the public key.
- In your AWS Cloud9 instance, on the left pane, click the Settings icon. Click Show Home in Favorites and Show Hidden Files, as shown in the screenshot below.
This should display the .ssh folder in the tree view.
- Expand the .ssh folder and open the authorized_keys file.
- Paste the public key you copied earlier in the authorized_keys file.
- Save the authorized_keys file. By updating this file, you are telling your AWS Cloud9 instance to allow connections that authenticate with the matching private key.
- Make a note of the public IP address of your AWS Cloud9 instance.
- Open PuTTY.
- In the left tree view, under Session, for HostName, type ec2-user@ CLOUD9-PUBLIC-IP. Make sure to replace CLOUD9-PUBLIC-IP with the public IP of your AWS Cloud9 instance.
- Under SSH -> Auth, click Browse and select the private key you created in the third exercise.
- Under Tunnels, for Source Port, type 5000, and for Destination, type localhost:5000.
- Click Add.
- Under Session, for Saved Sessions, type a name for the session and click Save to save the session for future reference.
- Click Open at the bottom.
- When you get a prompt message like the one below, click Yes.
You have now established an SSH tunnel to your AWS Cloud9 instance.
6. Test the application.
- To test the application, type http://localhost:5000 in your browser. You should see your application with a message that reads, Click log in/sign up to access this site.
- Click Log in/sign up at the top right corner of the application and sign up for the application. This will take you through the email verification process and create an entry in the Amazon Cognito user pool directory.
- Upload a few photos and notice that there is a description text box that you can use to add a description to your photos.
- Click My photos at the top-right corner of the application. You should see your uploaded photos.
- Click Home. You should see a message that reads, Click my photos to access your photos. These means your photos are being saved and retrieved against your login.
- Sign out of the application and click Home.
- You should see a message that reads, Click log in/sign up to access this site. This means that you are now being authenticated to access your photos saved in the database via Amazon Cognito.
Optional Advanced Challenge 1
This one is an advanced challenge: can you add Log in with Amazon as a feature to your application?
- First you'll need to create an application with Log in with Amazon. For more information, see Getting Started for Web.
- In Cognito User Pools, you will need to add Log in with Amazon as an identity provider. For more information, see Configuring Federation with a Social Identity Provider.
- Enable Log in with Amazon as an identity provider with your Amazon Cognito app client
- The application wants a nickname. This will need to be mapped from a Log in With Amazon attribute to a User Pool attribute.
Optional Advanced Challenge 2
A second advanced challenge: the code is currently signing out users after the Amazon Cognito access_token expires. See below. expires = datetime.utcfromtimestamp(session['expires'])
expires_seconds = (expires - datetime.utcnow()).total_seconds()
if expires_seconds < 0:
return None
The refresh_token
from the Cognito response is being stored in a session variable. Instead of signing users out when the access_token
expires, you can exchange the refresh_token
for id_token
and access_token
. For more information, see TOKEN Endpoint. Replace the return None
code above with code to exchange the refresh_token
. If successful, the user session can be repopulated and logged in with flask_login.login_user
.
7. Stop the Amazon RDS database instance
In order to keep your AWS account bill at a minimum, consider stopping the Amazon RDS instance and then starting it again when needed. Follow the steps below to stop the Amazon RDS database instance.
- In the AWS Console, click Services, then click Relational Database Service to open the Amazon RDS dashboard.
- In the left navigation pane, click Instances. In the list of instances, select edx-photos-db.
- At the top, click Instance actions, and then Stop. You will see a prompt. Click Yes, stop now.
眼镜蛇