Setting Up Authentication on AWS Amplify

Using Amazon Web Services Console

/Screenshot_2019-08-15_14-49-13-aws-signin.png

Creating an AWS Account

It is necessary to provide a payment method (Credit or Debit card) to use AWS, including the free tier. Be careful about this - many people have complained that they end up getting charged surprise fees even though they never intended to go over the data caps for the “free” services.

Creating a Sub-user

While it is possible to use your root AWS account for managing services, this is not recommended. The principle of least access is that no account should have more privilege than is needed. This will limit potential fallout in the case that any of your account keys are breached. Those familiar with UNIX systems understand that the root user is not meant to be used for normal operations, and in AWS it is recommended that you create a sub-user for managing AWS services. This is kind of like having a luxury car that has a “valet key”, which is basically a key that can start the engine, but won’t allow the glove-box or trunk to be opened (to prevent theft).

/Screenshot_2019-08-15_13-59-39-aws-iam.png
  • Navigate to IAM (Identity and Access Management) through the “find services” portal.
/Screenshot_2019-08-15_14-11-57-aws-manage-users.png
  • Navigate to the Create individual IAM users tab and select “Manage Users”
  • Select “add user” and provide a descriptive name for the account.

  • So-called Programmatic Access is a user (often a program) that can interface through the API.

  • The AWS Management Console is a user (often a human) that interacts with services through the AWS website (which they describe as the Management Console).

  • Proceed to next screen; permissions.

  • Set the permissions that you require ( Attach existing directly )

  • Proceed to next screen; tags

  • Add any descriptive tags that you may require for this user.

  • Proceed to next screen; review

  • Review the information before selecting “Create User”

  • Copy the secret key. After leaving this screen it will not again be accessible, and you would have to generate a new key.

  • Make sure to keep the key in a safe place, such as a password manager.

  • The credentials.csv from Download.csv contains these keys, and also a console login link you can use to sign in to an IAM sub-user account you have created.

  • The console login link is also available at the IAM Management Console

  • You will need the Access key ID and Secret access key to configure awsmobile

/Screenshot_2019-08-15_15-06-33-aws-console-login-link.png
  • Make sure to lock down the root user account with multi-factor authentication (MFA), and use it only for emergency access.
  • Sign out, and from then on always use the IAM users sign-on link to log in with IAM sub-user accounts you have created.

Some AWS Terminology

  • AWS Amplify - Getting mobile developers up and running quickly, using industry-standard best practices.

    • Dashboard for managing multiple AWS services (DynamoDB, Cognito, Pinpoint, etc..)
    • Out of the box with “good” configurations - inherently scalable.

      • Authentication (Cognito)
      • Storage (S3)
      • Serverless functions (AWS Lambda, or gateway to legacy API)
      • Database (DynamoDB)
      • Hosting (S3 and Cloudfront)
      • Analytics and Notifications (Pinpoint)
    • JavaScript bindings for working with AWS

      • aws-amplify-react - aws-amplify-react-native
  • AWS AppSync

    • GraphQL as a service. Can spin-up databases easily.
    • Can be built on top of DynamoDB, Elastic Search, or Lambda functions.
    • Can be used with AWS Amplify and Mobile Hub

Getting Started with amplify

  • install @aws-amplify/cli globally with

    npm install -g @aws-amplify/cli

  • set access keys (from IAM steps above) and select your region with

    amplify configure

  • Create new project with

    amplify init

Intelligent amplify init can sense if it is inside of a Create-React-App

OH NO!

If you were working based off materials older than a few months, you might have tried awsmobilehub This is what you would have then been confronted with:

/Screenshot_2019-08-17_13-20-24-aws-mobile-deprecation.png
Apparently awsmobile-cli is not developed anymore.

This is the kind of thing that happens a lot in web development, because it tends to be very fast moving. It’s not uncommon for something to become totally obsolete within 12 months. The tutorial I’m working with is no more than 12 months old, and already obsolete! A lot of what makes a good developer is the sixth sense of how to move forward in these types of situations. At least in this case, the recommendation is clear:

npm install -g @aws-amplify/cli

Successfully installed the Amplify CLI

Javascript Getting Started - https://aws-amplify.github.io/docs/js/start Android Getting Started - https://aws-amplify.github.io/docs/android/start iOS Getting Started - https://aws-amplify.github.io/docs/ios/start

Getting started with Amplify Framework

/Screenshot_2019-08-17_13-58-06-amplify-framework.png
amplify configure
Follow these steps to set up access to your AWS account:

Sign in to your AWS administrator account:
https://console.aws.amazon.com/
Press Enter to continue

Specify the AWS Region
? region:  us-east-1
Specify the username of the new IAM user:
? user name:  amplify-app
Complete the user creation using the AWS console
https://console.aws.amazon.com/iam/home?region=undefined#/users$new?step=final&accessKey&userNames=amplify-app&permissionType=policies&policies=arn:aws:iam::aws:policy%2FAdministratorAccess
Press Enter to continue

Enter the access key of the newly created user:
? accessKeyId:   AKIA5CM2WX**********
? secretAccessKey:  /DdbLSPrmgrU3HXUrxNK********************
This would update/create the AWS Profile in your local machine
? Profile Name:  default

Successfully set up the new user.


amplify init
Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project Recipe Trader Mobile
? Enter a name for the environment dev
? Choose your default editor: IDEA 14 CE
? Choose the type of app that you're building javascript
Please tell us about your project
? What javascript framework are you using react-native
? Source Directory Path:  src
? Distribution Directory Path: dist/app-amplify
? Build Command:  npm run-script build
? Start Command: npm run-script start
Using default provider  awscloudformation

For more information on AWS Profiles, see:
https://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html

? Do you want to use an AWS profile? Yes
? Please choose the profile you want to use default
⠧ Initializing project in the cloud...

CREATE_IN_PROGRESS recipetradermobile-dev-20190815193604 AWS::CloudFormation::Stack Thu Aug 15 2019 19:36:04 GMT-0400 (Eastern Daylight Time) User Initiated             
CREATE_IN_PROGRESS DeploymentBucket                      AWS::S3::Bucket            Thu Aug 15 2019 19:36:08 GMT-0400 (Eastern Daylight Time)                            
CREATE_IN_PROGRESS UnauthRole                            AWS::IAM::Role             Thu Aug 15 2019 19:36:08 GMT-0400 (Eastern Daylight Time)                            
CREATE_IN_PROGRESS AuthRole                              AWS::IAM::Role             Thu Aug 15 2019 19:36:08 GMT-0400 (Eastern Daylight Time)                            
CREATE_IN_PROGRESS UnauthRole                            AWS::IAM::Role             Thu Aug 15 2019 19:36:09 GMT-0400 (Eastern Daylight Time) Resource creation Initiated
CREATE_IN_PROGRESS AuthRole                              AWS::IAM::Role             Thu Aug 15 2019 19:36:09 GMT-0400 (Eastern Daylight Time) Resource creation Initiated
CREATE_IN_PROGRESS DeploymentBucket                      AWS::S3::Bucket            Thu Aug 15 2019 19:36:09 GMT-0400 (Eastern Daylight Time) Resource creation Initiated
⠸ Initializing project in the cloud...

CREATE_COMPLETE UnauthRole AWS::IAM::Role Thu Aug 15 2019 19:36:23 GMT-0400 (Eastern Daylight Time) 
CREATE_COMPLETE AuthRole   AWS::IAM::Role Thu Aug 15 2019 19:36:23 GMT-0400 (Eastern Daylight Time) 
⠧ Initializing project in the cloud...

CREATE_COMPLETE DeploymentBucket                      AWS::S3::Bucket            Thu Aug 15 2019 19:36:30 GMT-0400 (Eastern Daylight Time) 
CREATE_COMPLETE recipetradermobile-dev-20190815193604 AWS::CloudFormation::Stack Thu Aug 15 2019 19:36:32 GMT-0400 (Eastern Daylight Time) 
✔ Successfully created initial AWS cloud resources for deployments.
✔ Initialized provider successfully.
Initialized your environment successfully.

Your project has been successfully initialized and connected to the cloud!

Some next steps:
"amplify status" will show you what you've added already and if it's locally configured or deployed
"amplify <category> add" will allow you to add features like user login or a backend API
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

Pro tip:
Try "amplify add api" to create a backend API and then "amplify publish" to deploy everything

Amplify Init

$> amplify init
✔ Successfully created initial AWS cloud resources for deployments.
✔ Initialized provider successfully.
Initialized your environment successfully.

Your project has been successfully initialized and connected to the cloud!

Some next steps:
"amplify status" will show you what you've added already and if it's locally configured or deployed
"amplify <category> add" will allow you to add features like user login or a backend API
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

Pro tip:
Try "amplify add api" to create a backend API and then "amplify publish" to deploy everything

Connecting AWS Amplify

The file aws-exports.js is automatically added to the source folder specified in during the init This file is not for edit - but it contains the configuration for AWS.

Create link between frontend and backend by adding this to app root component file (index.js)

import Amplify from 'aws-amplify';
import configuration from './src/aws-exports';

Amplify.configure(configuration);

Amplify Configuration

According to documentation Rather than configuring each service through a constructor or constants file, Amplify supports configuration through a centralized file called aws-exports.js which defines all the regions and service endpoints to communicate. Whenever you run amplify push, this file is automatically created allowing you to focus on your application code. The Amplify CLI will place this file in the appropriate source directory configured with amplify init.

Adding Client-Side Authentication

AWS Amplify Documentation aws-amplify-cli The documentation provides some clues

In the Amplify ecosystem, the most common Authentication method is either using Cognito User Pools independently or with a social provider to validate the identity of the user (known as Federation).

$> amplify add auth

Using service: Cognito, provided by: awscloudformation

 The current configured provider is Amazon Cognito. 

 Do you want to use the default authentication and security configuration? (Use arrow keys)
❯ Default configuration 
  Default configuration with Social Provider (Federation) 
  Manual configuration 
  I want to learn more. 

 Do you want to use the default authentication and security configuration? I want to learn more.

This utility allows you to set up Amazon Cognito User Pools and Identity Pools for your application.

Amazon Cognito User Pool makes it easy for developers to add sign-up and sign-in functionality to web and mobile
 applications. It serves as your own identity provider to maintain a user directory. It supports user registrati
on and sign-in, as well as provisioning identity tokens for signed-in users.

Amazon Cognito identity pools provide temporary AWS credentials for users who are guests (unauthenticated) and f
or users who have been authenticated and received a token. An identity pool is a store of user identity data spe
cific to your account.

If you choose to use the default configuration, this utility will set up both a Userpool and an Identity Pool.

If you choose the 'Default configuration with Social Provider (Federation)', the providers will be federated wit
h Cognito User Pools.

In either case, User Pools will be federated with Identity Pools allowing any users logging in to get both ident
ity tokens as well as AWS Credentials.

 Do you want to use the default authentication and security configuration? Manual configuration
 Select the authentication/authorization services that you want to use: I want to learn more.

Amazon Cognito identity pools provide temporary AWS credentials for users who are guests (unauthenticated) and f
or users who have been authenticated and received a token. An identity pool is a store of user identity data spe
cific to your account.

If you choose to use the default configuration, this utility will set up both a Userpool and an Identity Pool.

 Select the authentication/authorization services that you want to use: User Sign-Up, Sign-In, connected with AW
S IAM controls (Enables per-user Storage features for images or other content, Analytics, and more)
 Please provide a friendly name for your resource that will be used to label this category in the project: ampli
fyAuthentication
 Please enter a name for your identity pool. recipe_trader_mobilea09bb47c_identitypool_a09bb47c
 Allow unauthenticated logins? (Provides scoped down permissions that you can control via AWS IAM) I want to lea
rn more.

If you select 'yes', your identity pool will provide temporary AWS credentials for unauthenticated guest users.


 Allow unauthenticated logins? (Provides scoped down permissions that you can control via AWS IAM) Yes
 Do you want to enable 3rd party authentication providers in your identity pool? I want to learn more.

If you select yes, your identity pool will support users who are authenticated via a public login provider such 
as Facebook, Google, and Amazon (non-Cognito).  Your identity pool will continue to support users who are authen
ticated via a user pool.


 Do you want to enable 3rd party authentication providers in your identity pool? Yes
 Select the third party identity providers you want to configure for your identity pool: 
 Please provide a name for your user pool: recipe_trader_mobilea09bb47c_userpool_a09bb47c
 Warning: you will not be able to edit these selections. 
 How do you want users to be able to sign in? I want to learn more.

Selecting 'Email' and/or 'Phone Number' will allow end users to sign-up using these values.  Selecting 'Username
' will require a unique username for users.


 How do you want users to be able to sign in? Username
 Multifactor authentication (MFA) user login options: OFF
 Email based user registration/forgot password: Enabled (Requires per-user email entry at registration)
 Please specify an email verification subject: Your verification code
 Please specify an email verification message: Your verification code is {####}
 Do you want to override the default password policy for this User Pool? No
 Warning: you will not be able to edit these selections. 
 What attributes are required for signing up? (Press <space> to select, <a> to toggle all, <i> to invert selecti
on)Email
 Specify the app's refresh token expiration period (in days): 30
 Do you want to specify the user attributes this app can read and write? No
 Do you want to enable any of the following capabilities? (Press <space> to select, <a> to toggle all, <i> to in
vert selection)
 Do you want to use an OAuth flow? Yes
 What domain name prefix you want us to create for you? recipetrader
 Enter your redirect signin URI: 
>> The value must be a valid URI with a trailing forward slash. HTTPS must be used instead of HTTP unless you ar
e using localhost.

Default configurations are designed to be secure by default.

$> amplify add auth

Using service: Cognito, provided by: awscloudformation

 The current configured provider is Amazon Cognito. 

 Do you want to use the default authentication and security configuration? Default configuration
 Warning: you will not be able to edit these selections. 
 How do you want users to be able to sign in? Username
 Do you want to configure advanced settings? No, I am done.
Successfully added resource recipetradermobile3c7a817b locally

Some next steps:
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

$> amplify push

Current Environment: dev

| Category | Resource name              | Operation | Provider plugin   |
| -------- | -------------------------- | --------- | ----------------- |
| Auth     | recipetradermobile3c7a817b | Create    | awscloudformation |
? Are you sure you want to continue? Yes
⠼ Updating resources in the cloud. This may take a few minutes...

UPDATE_IN_PROGRESS recipetradermobile-dev-20190815193604 AWS::CloudFormation::Stack Sat Aug 17 2019 15:08:13 GMT-0400 (Eastern Daylight Time) User Initiated             

...

CREATE_COMPLETE                     UpdateRolesWithIDPFunctionOutputs     Custom::LambdaCallout      Sat Aug 17 2019 15:10:23 GMT-0400 (Eastern Daylight Time) 
UPDATE_COMPLETE_CLEANUP_IN_PROGRESS recipetradermobile-dev-20190815193604 AWS::CloudFormation::Stack Sat Aug 17 2019 15:10:26 GMT-0400 (Eastern Daylight Time) 
UPDATE_COMPLETE                     recipetradermobile-dev-20190815193604 AWS::CloudFormation::Stack Sat Aug 17 2019 15:10:26 GMT-0400 (Eastern Daylight Time) 
✔ All resources are updated in the cloud

Checking out that it worked

$> amplify console auth
Using service: Cognito, provided by: awscloudformation
? Which console Both

Brings you to the AWS console website where you can inspect the User Pool and the Identity Pool

Add authentication

import {withAuthenticator} from 'aws-amplify-react-native';

wrap the Application component

export default Application
=> change to =>
export default withAuthenticator(Application)

Rookie Mistake

Using both aws-amplify-react and aws-amplify-react-native will create problems. The aws-amplify-react module is not meant to be used with React Native. This is because CSS cannot be parsed in RN.

If everything does work, you should now be directed to the login screen when you start the app.

/Screenshot_2019-08-17_16-33-22-auth-screen.png

yarn add aws-amplify-react-native

Amazon Cognito

Amazon Cognito handles the entire authorization backend for us. A Cognito User Pool is a database of users, managed by Amazon. AWS Amplify implements user sign-up, sign-in, and sign-out flows. Cognito uses JSON Web Tokens to authenticate user sessions. With the Amplify library, there is no need to manually manage or refresh these tokens.

Select “Manage User Pools” from the Amazon Cognito console

/Screenshot_2019-08-20_11-52-46-manage-user-pools.png

  • Then select “Create User Pool”
  • Provide a name.
  • Select Step Through Settings
  • Sign in with verified email is generally sufficient.

Set your password policy

/Screenshot_2019-08-20_11-58-04-select-password-policy.png

Add the apps you want this user pool to work with.

/Screenshot_2019-08-20_12-01-47-add-apps.png

Enable sign-in API for server-based authentication (ADMIN_NO_SRP_AUTH) is useful for development purposes (using API key and secret)

If everything works, you should see a message confirming the creation of your new user pool.

You can grab your USER_POOL_ID for use in your app

/Screenshot_2019-08-20_12-30-24-user-pool-created-success.png

Grab the APP_CLIENT_ID from General settings > App clients

/Screenshot_2019-08-20_12-35-02-app-client-id.png

Integrate into your own app by adding something like the following

import Amplify from 'aws-amplify';
import config from './config';

Amplify.configure({
    Auth: {
        mandatorySignIn: true,
        region: config.cognito.REGION,
        userPoolId: config.cognito.USER_POOL_ID,
        userPoolWebClientId: config.cognito.APP_CLIENT_ID,
    }
});