Cognito with Amplify and React

Requirements

  • AWS CLI;

  • Node and npm;

  • Amplify CLI (npm install -g @aws-amplify/cli )

Configure amplify

Run:

amplify configure

Sample output:

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

It will launch a new tab on your browser, log in to your AWS console and press Enter on your terminal.

Select your AWS Region (where Cognito stack will be created). Press enter.

Specify an user name (you can use the default) for the new Cognito IAM user. This user will be used by Cognito to create all resources.

It will launch a new tab on your browser to create the user. Click on Next: Permissions. Use de policies already selected. Click on Next: Tags -> Next: Review -> Create User.

Copy and save the Access key ID and Secret access key . Those credentials will not be displayed again.

Press enter on your terminal.

Input the credentials created.

Select your AWS CLI profile to be created or updated.

Creating the React project

npx create-react-app amplify-auth-demo
cd amplify-auth-demo

Install the Amplify library:

npm install --save aws-amplify

Creating the Amplify project

Run:

amplify init
  • Enter a name for the project: amplifyauth (or your preferred project name)

  • Enter a name for the environment: local (or your preferred environment name)

  • Choose your default editor: Visual Studio Code (or your text editor)

  • Choose the type of app that you're building: javascript

  • What javascript framework are you using: react

  • Source Directory Path: src

  • Distribution Directory Path: build

  • Build Command: npm run-script build

  • Start Command: npm run-script start

  • Do you want to use an AWS profile? Y

  • Please choose the profile you want to use: YOUR_USER_PROFILE

Creating our App IDs

Facebook

Go to: https://developers.facebook.com/

Click on My Apps, Create App.

Fill up the form and click on Create App ID.

Go to Setting-> Basic and copy your app credentials.

Google

Go to: https://console.developers.google.com/apis/credentials

On the left navigation bar, choose OAuth consent screen.

Input only your Application name for now and click on Save.

On the left navigation bar, choose Credentials.

Create your OAuth2.0 credentials by choosing OAuth client ID from the Create credentials drop-down list.

Choose Web application.

Click on Create.

Copy and save the credentials.

Creating and configuring the authentication service

Run:

amplify add auth

Run amplify update auth if you already have a project configured & want to now add Social login

This will walk us through a series of steps:

  • Do you want to use the default authentication and security configuration? Default configuration with Social Provider (Federation)

  • How do you want users to be able to sign in when using your Cognito User Pool? Username

  • Do you want to configure advanced settings? Yes, I want to make some additional changes.

  • What attributes are required for signing up? Email

  • Do you want to enable any of the following capabilities? None, press Enter.

  • What domain name prefix you want us to create for you? amplifyauthXXXXXXXXX (use default or create custom prefix)

  • Enter your redirect signin URI: http://localhost:3000/ (this can be updated later for production environments)

  • Do you want to add another redirect signin URI: N

  • Enter your redirect signout URI: http://localhost:3000/ (this can be updated later for production environments)

  • Do you want to add another redirect signout URI: N

  • Select the social providers you want to configure for your user pool: Choose Facebook & Google

  • Enter your Facebook App ID for your OAuth flow.

  • Enter your Facebook App Secret for your OAuth flow.

  • Enter your Google Web Client ID for your OAuth flow.

  • Enter your Google Web Client Secret for your OAuth flow.

Run and confirm:

amplify push

After running amplify push you should see a success message & the OAuth Endpoint should also be logged out to the console:

Hosted UI Endpoint: https://amplifyauthe9a9d15d-e9a9d15d-local.auth.us-east-1.amazoncognito.com/
Test Your Hosted UI Endpoint: https://amplifyauthe9a9d15d-e9a9d15d-local.auth.us-east-1.amazoncognito.com/login?response_type=code&client_id=6kbge3h97np3jvtkv7rmkjlt1q&redirect_uri=http://localhost:3000/

This OAuth endpoint is also available for reference in src/aws-exports.js if you need it at any point under the oauth -> domain key.

We will need to use this endpoint to finish configuring our Facebook & Google Oauth providers.

Configure Social Provider Federation

Facebook

Go to Settings -> Basic. Scroll all the way down and click on + Add Platform.

Choose website.

For the _Site URL), input the OAuth Endpoint URL with /oauth2/idpresponse appended into Site URL:

Save changes.

Next, from the navigation bar choose Productsand then Set up from Facebook Login.

Choose Web.

For the Valid OAuth Redirect URIs use the OAuth Endpoint + /oauth2/idpresponse. If you're prompted for the site URL, also use this endpoint (i.e. https://amplifyauthe9a9d15d-e9a9d15d-local.auth.us-east-1.amazoncognito.com/oauth2/idpresponse):

Save changes.

Paste your OAuth Endpoint into App Domains and input Privacy and Terms of Service URL (it is requirement to go live).

Make sure your app is Live by clicking the On switch at the top of the page.

Select a category and click con Switch mode.

Google

Go to OAuth consent screen. Add your OAuth Endpoint domain into Authorized domains and click on Save.

Open your Client:

Input your OAuth Endpoint into Authorized JavaScript origins .

Input your OAuth Endpoint with /oauth2/idpresponse into Authorized redirect URIs.

Click on Save.

Configure the React application

We do this by adding the following code below our last import in src/index.js:

import Amplify from 'aws-amplify'
import config from './aws-exports'
Amplify.configure(config)

Next, open App.js and update the code to the following:

import React from 'react'
import logo from './logo.svg'
import './App.css'

import { Auth } from 'aws-amplify'

function checkUser() {
  Auth.currentAuthenticatedUser()
    .then(user => console.log({ user }))
    .catch(err => console.log(err))
}

function signOut() {
  Auth.signOut()
    .then(data => console.log(data))
    .catch(err => console.log(err))
}

function App(props) {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <button onClick={() => Auth.federatedSignIn()}>Sign In</button>
        <button onClick={checkUser}>Check User</button>
        <button onClick={signOut}>Sign Out</button>
      </header>
    </div>
  )
}

export default App

Now, run the app:

npm start

References

https://dev.to/dabit3/the-complete-guide-to-user-authentication-with-the-amplify-framework-2inh

Last updated