Amplify Gen 2 — Authentication for Applications with Amazon Web Services (AWS)
Managing users in the era of software, mobile, native, and web applications is a building complexity with the considerations of data, security, and privacy. Allowing people to create digital accounts to interact with your community creates usership and extends the reach of your brand. Services within AWS make usership development simple and secure with the Amplify platform and the included collocated and powerful additional features.
Amazon Web Services (AWS) provides a simplified platform with Authorization, enabled with “Sign Up, “Account Confirmation”, and “Sign Out” functionality, Amplify is hosted in a secure framework in Amazon Web Services (AWS) with a programmatically accessible SDK.
https://aws.amazon.com/amplify
In the initial setup of Amplify Gen 2, there are a few initial steps that need to be taken to provide access to the simplified deployment and sandbox environment. Amazon Web Services (AWS) provides exceptional documentation for integrating Amplify Gen 2 with multiple frontend frameworks, the following further explains the impact of downstream choices through the process.
As a primary step to accessing any Amazon Web Services (AWS) from your local machine, you will need to install the AWS CLI if you have not already. You can find the latest version for your computer on the AWS Documentation site. Once installed you can follow along with the rest of the steps to go from cloud to local environment and then back once deployed.
Creating an Amplify user
In this step of Amplify Gen 2, you can begin by visiting the IAM Identity Center, which is a simplified portal focused on reducing the complexity of IAM tasks for enterprise and organization cloud admins. In this step you will enable IAM Identity Center and use the Python SDK Boto script to create a user and assign IAM permissions for deploying and connecting to Amplify.
On the “IAM Identity Center” page, click “Enable” to enable these services for your cloud region.
On the “IAM Dashboard” page, in the bottom left corner click to open the “CloudShell” Command Line Interface (CLI). Using the CloudShell CLI allows for a secure and permissioned environment running within AWS and a runtime to assign permission which may not be configured yet on your local machine.
In the CloudShell CLI, paste then press enter to run the following command, providing the email to be used for the Amplify admin user.
read -p "Enter email address: " user_email
Once the prompt has been run in CloudShell, enter the email address you would like to use for the Amplify admin user, then hit enter.
In the CloudShell CLI, paste then press enter to run the Python/Boto script and create the Amplify admin user.
response=$(aws sso-admin list-instances)
ssoId=$(echo $response | jq '.Instances[0].IdentityStoreId' -r)
ssoArn=$(echo $response | jq '.Instances[0].InstanceArn' -r)
email_json=$(jq -n --arg email "$user_email" '{"Type":"Work","Value":$email}')
response=$(aws identitystore create-user --identity-store-id $ssoId --user-name amplify-admin --display-name 'Amplify Admin' --name Formatted=string,FamilyName=Admin,GivenName=Amplify --emails "$email_json")
userId=$(echo $response | jq '.UserId' -r)
response=$(aws sso-admin create-permission-set --name amplify-policy --instance-arn=$ssoArn --session-duration PT12H)
permissionSetArn=$(echo $response | jq '.PermissionSet.PermissionSetArn' -r)
aws sso-admin attach-managed-policy-to-permission-set --instance-arn $ssoArn --permission-set-arn $permissionSetArn --managed-policy-arn arn:aws:iam::aws:policy/service-role/AmplifyBackendDeployFullAccess
accountId=$(aws sts get-caller-identity | jq '.Account' -r)
aws sso-admin create-account-assignment --instance-arn $ssoArn --target-id $accountId --target-type AWS_ACCOUNT --permission-set-arn $permissionSetArn --principal-type USER --principal-id $userId
The output of the CloudShell CLI should contain a “Start session url”, make sure to copy and paste that into your browser and bookmark the link for later. After this step has been completed, in the left side menu, click “Users” to open the “Users” page, then on the “Users” page click the “amplify-admin” that you generated in the last step.
On the “amplify-admin” page you should see a banner that says, “Email not verified” at the top of the page, with a button that says “Send email verification link”. Click the “Send email verification link” button to begin the process of sending a verification email to the email you provided in previous steps.
On the “amplify-admin” page you should see a banner that says, “Email not verified” at the top of the page, with a button that says “Send email verification link”. Click the “Send email verification link” button to begin the process of sending a verification email to the email you provided in previous steps.
In the “Send email verification link” modal that appears, click the “Send” button to complete the request for sending an email verification link and verifying your recently created user. Once you receive the email and verify the account, on the same “amplify-user” page, click the “Reset password” button in the top right corner of the page.
In the “Reset password for user amplify-admin” modal, check the option “Generate a one-time password and share the password with the user”, then click the “Reset password” button. This will generate a password within the AWS platform.
Actions performed within AWS are secure in the permissioned environment, in addition to the verified environment, this password is never shared across email which is more secure.
After receiving the email, go to the “Start session url” to login to the new user which you recently created, this will allow for adding an authenticator, changing the password, and creating a profile for enabling local access to the AWS resources which are connected to the account.
After signing in via the “Start session url”, adding an authenticator, and creating a new password, AWS will prompt you with a modal that says “Allow botocore-client-amplify-admin” to access your Data?”, in this modal click the “Allow access” button.
Once you have allowed the Python SDK Boto to access the account, you are now ready to use this account locally for development, sandboxes, and establishing a connection to Amplify Gen 2.
Configuring your Amplify locally
In Amplify Gen 2 technologies are still integrated with the major services of AWS like, Cognito user pools for facilitating authentication. A focus of profiles is set as the method of security for locally accessing sandboxes, these profiles are stored in the AWS configuration file.
In your terminal, paste and enter the below snippet to initialize your local AWS credentials profile.
aws configure sso
The command line will proceed with a series of questions, to finish this process answer the following questions:
Enter a name for the environment: <Project Name>
SSO session name (Recommended): amplify-admin
SSO start URL [None]: https://<YOUR_ENVIRONMENT>.awsapps.com/start
SSO region [None]: <YOUR_REGION>
SSO registration scopes [sso:account:access]: ""
Once these questions are answered, the CLI will provide a url to visit and a code to enter, to authenticate, complete these two actions and return to the CLI:
CLI default client Region [None]: <YOUR_REGION>
CLI default output format [None]: ""
CLI profile name [amplify-policy-<YOUR_ACCOUNT_ID>]: default
After completing the second set of questions, the local profile for AWS is stored which now allows for future commands to be run, using that profile, with the --default
flag.
Implementing Amplify in React
When enabling Amplify Gen 2 locally it is required to first establish the Amplify credentials for the backend and authentication source. Once the Amplify credentials are available as files within your local repository, you can then run a sandbox environment which replicates the live environment to allow for local development.
To begin this process of implementing Amplify, the ideal location to store the amplify files is within the src
folder for a Create React App application, this mitigates downstream reference errors for the amplify_outputs.json
file. In your terminal, from the root folder of your application, type and enter cd src
to change to the source directory for implementing your Amplify configuration. In your terminal, paste and enter the below snippet to initialize Amplify Gen 2 within your application.
npm create amplify@latest --force
Following the steps provided in the CLI by NPM, you will be prompted as to where to install the dependencies and the required files, you can choose “.” as the primary folder for the installation. Once Amplify is setup, delete the node_modules
folder and the package-lock.json
from the src
folder, then in your terminal return to the root folder with cd ..
and paste and enter the below snippet to reinstall your dependencies.
npm install --force
Again, in your terminal, paste and enter the below snippet to initialize the sandbox for Amplify Gen 2 within your application.
npx ampx sandbox --profile default
If your profile for Amplify Admin worked and has no conflicts, Amplify will start streaming the sandbox to your local machine. If you have an existing profile that is creating conflicts, go to your AWS folder within the user folder on your computer, it should be named the same as the user which you use to access your machine, and delete the AWS folder. After deleting the AWS folder, paste and enter the following in your terminal.
npx ampx configure profile
Once your resources are fully running, you can use the Amplify Gen 2 features locally now that they are established within your code. The following sections will show you the final steps for implementing Amplify Gen 2 now that you have authorized your computer to access the Amplify cloud.
Coding a Sign-up Form
Developing a sign-up form with Amplify takes a few steps, the implementation is simple, and works with the AWS SDK to invoke API commands through HTML form element which collect the data and pass the values to the API payload.
You can use a framework like Formik for implementing the form, adding validation, and presenting errors, which can be quickly scaffolded to intake the required data fields for the form. In your terminal, paste and enter the below snippet to install Formik within your React application.
npm install formik
In this use-case you can use, the useFormik()
hook that will extract the Formik package and allow your React form to utilize its features, leaving room for customization.
import * as React from "react";
import { Amplify } from "aws-amplify";
import { useFormik } from "formik";
import * as Yup from "yup";
import { signUp } from "aws-amplify/auth";
import outputs from "./amplify_outputs.json";
Amplify.configure(outputs);
async function signUpF(values) {
try {
const { username, password } = values;
const { user } = await signUp({
username: username,
password: password,
options: {
userAttributes: {
email: username,
},
},
});
console.log(user);
alert(JSON.stringify(user, null, 2));
} catch (error) {
console.log("error signing up:", error);
}
}
function App() {
const formik = useFormik({
initialValues: {
username: "",
password: "",
},
validationSchema: Yup.object({
username: Yup.string().email().required(),
password: Yup.string().min(8).required(),
}),
onSubmit: async (values) => {
try {
const user = await signUpF(values);
if (user) {
console.log("user", user);
}
} catch (error) {
console.log("error signing up:", error);
}
},
});
return (
<>
<section>
<div>
<form onSubmit={formik.handleSubmit}>
<label htmlFor="username">Username/Email</label>
<span className="error">{formik?.errors?.username}</span>
<input
id="username"
name="username"
value={formik.values.username}
onChange={formik.handleChange}
/>
<label htmlFor="password">Password</label>
<span className="error">{formik?.errors?.password}</span>
<input
id="password"
name="password"
type="password"
value={formik?.values?.password}
onChange={formik.handleChange}
/>
<button className="button" type="submit" value="submit">
Sign up
</button>
</form>
</div>
</section>
</>
);
}export default App;
https://github.com/heyitsjoealongi/react-amplify-authentication-two/blob/main/src/App.js
Based on your authentication type configured in Amplify and your backend configuration, setup the form to collect and pass the parameters required for a successful sign-up. Once this form is established, and the onSubmit()
function is in place to pass the values forward to the SDK, you can utilize this form to begin signing up users for you application.
You can extend and add additional SDK functions with form components written in React JavaScript and Formik. You can find the example code, which was written when writing this tutorial, and is a combination of the Amazon Web Services (AWS) example code, Create React App, and React JavaScript code written for this blog.