# React Authentication made easy with useAuth0

Authentication is hard! Nowadays, to create a simple login or logout feature, we require a considerable amount of boilerplate code. Now picture we want to add authentication with Google or Facebook? More boilerplate, right?
What if I told you that in React you can do that just by wrapping your code with a context provider and by using a custom react hook?

In this blog post, I'll show you how to add authentication to your React application using the _Auth0_ `useAuth0` custom hook, how to display the authenticated user information, and how to authenticate with a social provider like _GitHub_.

# Setup
## Auth0 dashboard

So the first thing you need is an _Auth0_ account. You can sign up for free at https://auth0.com/signup.

Once you have your account setup, on the [application settings dashboard](https://manage.auth0.com/#/applications) create a new application with the _Single Page Web Application_ type.

![createApp.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1598553329288/-O_qNEaYQ.png 'Create a single page application')

Now that you have your application, you will need to get some data and do some configurations first, here's what you need to do:

- Copy your Domain value (we'll use it in the next step)
- Copy your Client ID value (we'll use it in the next step)

![domainClient.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1598553471309/z9K5-OJhx.png 'Domain and Client ID')

- Add `http://localhost:3000` to the Allowed Callback URLs so that it can call back to it after logging in
- Add `http://localhost:3000` to the Allowed Logout URLs so that it can redirect to it after logging out
- Add `http://localhost:3000` to the Allowed Web Origins to make it an allowed origin for use with Cross-Origin Authentication

![localhostToAllowed.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1598553517016/JnG-_QQcP.png 'Add localhost to required fields')

Now we configured everything on the dashboard, the next thing you will need is an application.

## React Application

On this project you should do two things first:

### 1. Install auth0-react SDK

```
npm install @auth0/auth0-react
```

### 2. Add your previously copied domain and client id to your .env file

```
REACT_APP_AUTH0_DOMAIN=<Add your domain here>
REACT_APP_AUTH0_CLIENTID=<Add your client id here>
```

Now we finished all the setup needed to add authentication to our application. To be able to make use of the `useAuth0` hook we need to wrap our application the _Auth0_ context provider.

# Auth0Provider

```js
import { Auth0Provider } from '@auth0/auth0-react'

ReactDOM.render(
  <Auth0Provider
    domain={process.env.REACT_APP_AUTH0_DOMAIN}
    clientId={process.env.REACT_APP_AUTH0_CLIENTID}
    redirectUri={window.location.origin}
  >
    <App />
  </Auth0Provider>,
  document.getElementById('root'),
)
```

On this snippet, we wrap our App component with the `Auth0Provider` which is a context provider that stores the authentication state of our users and allows for children of this component to access it.
This provider receives 3 parameters:

- the `domain` and `clientId` params which we can get thanks to our setup on the .env file
- the `redirectUri` which is the default _URL_ where _Auth0_ redirects the browser to with the authentication results. In the snippet above we use the _origin_ property from the _location_ object to get the current page _URL_

Having our App wrapped with the `Auth0Provider`, now we can start using the `useAuth0` hook.

# useAuth0

`useAuth0` is a custom React hook that's part of the _Auth0_ React SDK. This hook provides you with some helpers and functions that you can use to abstract all the authentication logic and often immense boilerplate code from your code.
On the next sections, I'll present you to some auth methods for login (`loginWithRedirect`) and logout (`logout`) as well as some auth state for obtaining the authenticated state (`isAuthenticated`) and the authenticated user date (`user`).

## Login

For adding the ability to login to your application, you can make use of the `loginWithRedirect` method.

```js
import { useAuth0 } from '@auth0/auth0-react'

const LoginButton = () => {
  const { loginWithRedirect } = useAuth0()
  return <button onClick={() => loginWithRedirect()}>Log In</button>
}
```

Here we show our `LoginButton` component. In this component, we destructure the `loginWithRedirect` method from the `useAuth0` hook and assign its call to the button `onClick` event. After pressing the button, you will be redirected to the [Auth0 Universal Login](https://auth0.com/universal-login) page where the user can either sign in or sign up.

![universalLoginPage.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1598553715668/oEAI4MR0p.png)

Note: if you want to avoid being redirected to a new page, you use instead the loginWithPopup method to open a popup with the [Auth0 Universal Login](https://auth0.com/universal-login) page.

## Logout

For adding the ability to log out to your application, you can make use the `logout` method

```js
import { useAuth0 } from '@auth0/auth0-react'

const LogoutButton = () => {
  const { logout } = useAuth0()
  return (
    <button onClick={() => logout({ returnTo: window.location.origin })}>
      Log Out
    </button>
  )
}
```

Here we show our `LogoutButton` component. In this component, we destructure the `logout` method from the `useAuth0` hook and assign its call to the button `onClick` event. This method receives a `returnTo` parameter where, thanks to the _origin_ property from the _location_ object, we specify the URL where _Auth0_ will redirect the browser after the logout process.

## Authentication State: isAuthenticated and User

As mentioned above, besides the functions that you gain access thanks to the `useAuth0` hook you also can access some authentication state properties like `isAuthenticated` and `user`

```js
import { useAuth0 } from '@auth0/auth0-react'

const Profile = () => {
  const { user, isAuthenticated } = useAuth0()
  return (
    isAuthenticated && (
      <div>
        <img src={user.picture} alt={user.name} />
        <h2>{user.name}</h2>
      </div>
    )
  )
}
```
Using isAuthenticated and user properties to display authenticated user information

In the snippet above, by combining the `isAuthenticated` property with the user property we guarantee that we'll only display the user data once we're sure that the user is authenticated.

# Bonus: Adding new social authentication within the Auth0 portal

By default on the [Auth0 Universal Login](https://auth0.com/universal-login) page, you'll only be able to use Google as a [Social Identity Provider](https://auth0.com/docs/connections/identity-providers-social). In this section, I'll show you how _Auth0_ makes it easy for you to add a new social provider to your application.

## Step 1

On the [application settings dashboard](https://manage.auth0.com/#/connections/social) go to the [social connections tab](https://manage.auth0.com/#/connections/social) to see all the currently configured social connections you have.
Click on the Create Connection button. ([Click here](https://manage.auth0.com/#/connections/social/create) to skip this and the previous step).

![addSocialConnection.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1598553875899/NBTWS1e_l.png)

## Step 2

Select one provider. In this example, I'll be choosing GitHub ([Click here](https://manage.auth0.com/#/connections/social/create/github) to skip this and the previous steps).

![selectConnection.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1598553899933/YoFmAlH5Z.png)

## Step 3

Scroll down and click on the Create button.

![addGithub.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1598553916750/lR-ubthkt.png)

## Step 4

You now can toggle this provider for your application.

![selectApp.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1598553933917/wJ6qtIcd9.png)

## Step 5

Try to log in on your application again.

![universalLoginPageWithGithub.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1598553948476/qMVRISKsB.png)

GitHub now shows up as an authentication option

# TLDR

Just in case you want a quick summary of everything here it is:

1. Create an _Auth0_ account at https://auth0.com/signup
2. Get the Domain and Client ID from your application at https://manage.auth0.com/#/applications and add them to your application .env
3. Configure your Allowed Callback URLs, in this case, add `http://localhost:3000`
4. Configure your Allowed Logout URLs, in this case, add `http://localhost:3000`
5. Configure your Allowed Web Origins, in this case, add `http://localhost:3000`
6. Install _Auth0_ React SDK
7. Wrap your main component with the Auth0Provider and add the domain, client id, and redirectUri parameters to it.
8. With the `useAuth0` hook, destructure the login method (loginWithRedirect or loginWithPopup) and create a login component
9. With the `useAuth0` hook, destructure the logout method and create a logout component
10. With the `useAuth0` hook, destructure the isAuthenticated variable and user properties to access authentication state inside a component

# What's next?

On the next posts of this series, I'll be showing you how to add protection to a route on your React application and how to use an Access Token to call a protected API.

Hope everyone enjoyed and stay tuned!

