# Cognito with Amplify and React

## Requirements

* AWS CLI;
* Node and npm;
* Amplify CLI (`npm install -g @aws-amplify/cli`  )

## Configure amplify

Run:

```bash
amplify configure
```

Sample output:

```bash
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&#x20;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

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

Install the Amplify library:

```bash
npm install --save aws-amplify
```

Creating the Amplify project

Run:

```bash
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`.

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXmhCkGjhoPwxGjaFe%2F-LuXoVDzcbXh2vwph-7i%2Fimage.png?alt=media\&token=f8935f70-a9d4-4547-9321-68cc88fe59d3)

Fill up the form and click on `Create App ID`.

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXmhCkGjhoPwxGjaFe%2F-LuXokBZMM0SUT0Bq07U%2Fimage.png?alt=media\&token=993bf64d-0043-45ca-a117-b1de353f0889)

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

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXmhCkGjhoPwxGjaFe%2F-LuXrMsTcx2M1IVM29kc%2Fimage.png?alt=media\&token=72701c6f-870c-4f7e-afee-59560b12fddc)

### Google

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

On the left navigation bar, choose `OAuth consent screen`.

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXmhCkGjhoPwxGjaFe%2F-LuXq5negGVQv7N02Ikg%2Fimage.png?alt=media\&token=51130679-442e-48fa-a46d-47dd7b54dcf8)

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

On the left navigation bar, choose Credentials.

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXmhCkGjhoPwxGjaFe%2F-LuXpM03hWxA3s7m3Gd0%2Fimage.png?alt=media\&token=05294669-7d75-4ba2-950c-3bd0aae06b9f)

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

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXmhCkGjhoPwxGjaFe%2F-LuXpaE4ZNx74mJ5sQna%2Fimage.png?alt=media\&token=7a0dcb26-8030-47ee-9726-3b83e5072ba3)

Choose Web application.

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXmhCkGjhoPwxGjaFe%2F-LuXqRzaWITO3QJsL3wm%2Fimage.png?alt=media\&token=bc69a8ec-40ac-4ba6-b1b2-48652a5bebb7)

Click on Create.

Copy and save the credentials.

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXmhCkGjhoPwxGjaFe%2F-LuXqbzoTqXRJSHdYwif%2Fimage.png?alt=media\&token=403de797-0e1e-45c3-ae6d-e27c0f18b793)

## Creating and configuring the authentication service

Run:

```bash
amplify add auth
```

{% hint style="info" %}
Run `amplify update auth` if you already have a project configured & want to now add Social login
{% endhint %}

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/**](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/**](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:

```bash
amplify push
```

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

```bash
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`.

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXsk3hcAQ3afxc9X4k%2F-LuXu1pfqSSG4_Tium6D%2Fimage.png?alt=media\&token=3f36658f-4097-4c8d-8eb4-fd60827791ff)

Choose website.

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXsk3hcAQ3afxc9X4k%2F-LuXuBPjYBj_HzO8EM1R%2Fimage.png?alt=media\&token=f4dbd0a3-1520-4c10-bf5e-90f415cb3193)

&#x20;For the \_Site URL), input the OAuth Endpoint URL with `/oauth2/idpresponse` appended into Site URL:

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXsk3hcAQ3afxc9X4k%2F-LuXuVPzn_gNq2Ex0W9m%2Fimage.png?alt=media\&token=01c38148-96eb-4a82-b22c-16c809a02c43)

Save changes.

Next, from the navigation bar choose `Products`and then `Set up from Facebook Login`.

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXsk3hcAQ3afxc9X4k%2F-LuXughq1Noc_YwAxgeI%2Fimage.png?alt=media\&token=d67e7ab6-3f40-47d0-b121-6c309d591813)

Choose `Web`.

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXsk3hcAQ3afxc9X4k%2F-LuXumoQR5CsIDP8iqWR%2Fimage.png?alt=media\&token=403ae396-1636-4cc8-b499-59b88e35d869)

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):](https://amplifyauth8e79c995-8e79c995-local.auth.eu-central-1.amazoncognito.com/oauth2/idpresponse\):)

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXsk3hcAQ3afxc9X4k%2F-LuXv7j40xJAvaTo7VSm%2Fimage.png?alt=media\&token=a97be8b3-b92d-4a71-93cf-eebd3d38af10)

Save changes.

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

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXsk3hcAQ3afxc9X4k%2F-LuXwCKTBbYyKIjYbAxs%2Fimage.png?alt=media\&token=fdefa08d-7cf1-46bb-9c99-e8fa676ffa0a)

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

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXsk3hcAQ3afxc9X4k%2F-LuXwWVD8kidfYCA89Cw%2Fimage.png?alt=media\&token=83b02337-5a44-4c49-8503-f75d5d56fa97)

Select a category and click con `Switch mode`.

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXsk3hcAQ3afxc9X4k%2F-LuXweIuzxPgPCy8GZoq%2Fimage.png?alt=media\&token=915794ba-97a4-493c-a91e-3f9c8cd48d47)

### Google

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

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXwjND_KxAUw7x10UA%2F-LuY-OmDeClOmXf-uaId%2Fimage.png?alt=media\&token=01eb2f96-75de-41a5-adb1-80fa3a7cc2d6)

Open your Client:

![](https://1923299483-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVfLS9KLUfusOjV0FX_%2F-LuXwjND_KxAUw7x10UA%2F-LuXzlSwiZgFfGEDxbQl%2Fimage.png?alt=media\&token=ed9e4827-b935-4f96-b715-07bde47be85b)

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

&#x20;We do this by adding the following code below our last import in `src/index.js`:

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

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

```javascript
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:

```bash
npm start
```

## References

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