How to build OAuth Provider Authentication with React and Altogic
Published: 2022-05-05 10:59:59


## Introduction

This article will cover OAuth Provider Authentication basics using **React** and [Altogic](https://www.altogic.com), a backend-as-a-service platform using its client library. You can checkout the [Github repository](https://github.com/altogic/altogic/tree/main/examples/react-oauth-provider-authentication) and the [demo application](https://altogic-react-oauth-provider-auth.vercel.app/).

**So, what is OAuth provider authentication?**

The term OAuth stands for Open Authorization with 3rd party application such as social providers. Users can sign in to the application using their **Google, Facebook, Twitter, Discord, Github** accounts.

Provider redirects us to the specific route in the application with *authorization token*. It is critical to emphasize that the shared content is *authorization token*, not your password data.
{% embed https://www.youtube.com/embed/tQJoT8bybMU %}
## How does the OAuth Provider Authentication work?

 1. Users select the OAuth provider from the frontend application

 2. After clicking the provider’s button, user is redirected related authorization page of the provider

 3. Users type their credentials on the providers sign in page

 4. The provider redirects user to the frontend application’s specific route called as **Development-Callback URL**

 5. The frontend application fetches and handles the response comes from the provider

## Creating App in Altogic

We can create an app with the [Altogic Designer](https://designer.altogic.com)** really fast. To create an app via the **Designer**:

 1. Log in to **Altogic** with your credentials.

 2. Select **New app**.

 3. In the **App name** field, enter a name for the app.

 4. And click **Create**.

![Creating App in Altogic](https://cdn-images-1.medium.com/max/2000/1*72gLAS71Uz3LnOsnWTqv_g.png)

Here, you can customize your subdomain, but not necessarily to do, **Altogic** automatically creates one for you, which will be your `envUrl`. You don’t need to worry if you lost your `envUrl`; you can get it from the **Environments** view of **Designer**.

![Getting the environment URL](https://cdn-images-1.medium.com/max/5020/1*UD9qNTdbnBgiD5ABedSeNQ.png)

After creating our app, we need `envUrl` and `clientKey` to access our app via Altogic Client Library to create a web application.

In order to get the `clientKey` we need to enter the app which we have created before and;

 1. Click on **App Settings** at the left-bottom of the designer.

 2. And click on **Client library keys** section.

![Getting Client Library Key](https://cdn-images-1.medium.com/max/5020/1*Svv6xGw7asGDmuBqSSsQPg.png)

We can create new `clientKey` from that page, but thanks to Altogic for creating one `clientKey` automatically for us, so let’s copy the existing `clientKey` from the list.

## How to Setup OAuth Provider Authentication with Altogic ?

**Altogic** currently supports 5 different **OAuth** providers:

* [Google](https://console.developers.google.com/)

* [Facebook](https://developers.facebook.com/)

* [Twitter](https://dev.twitter.com/)

* [Discord](https://discord.com/developers/docs/topics/oauth2)

* [Github](https://docs.github.com/en/developers/apps/building-oauth-apps/creating-an-oauth-app)

We can configure any of these providers and combine them. In this tutorial, we will learn the entire key points to configure the OAuth providers with our app.

The **Redirect URL** is the link to which your front-end application is redirected after the user signs in with the provider. Firstly, we will configure our frontend application’s *Redirect URL *with **Altogic.**

 1. Click on **App Settings** at the left-bottom of the **Designer**.

 2. And click on **Authentication** section.

 3. Type your **Redirect URL** to the input field.

![](https://cdn-images-1.medium.com/max/4064/1*65w0ycGb82et6UEeKwJuiw.png)

The remaining part is the configuration of the **oAuth** providers’ client with our app. We have to create an account with the providers we will use. As we indicate early, Altogic currently supports 5 different oAuth providers such as, **Google**, **Twitter**, **Facebook**, **LinkedIn**, and **Github**. We can view their configuration details at the bottom of this page. Before moving on to the self-configuration of each provider, there are 4 core concepts to explain:

* **Client ID:** The ID of the application on the provider side

* **Client Secret:** The secret client key of the application on the provider side

* **Development-Callback URL:** The Redirect URL that we will pass to the application on the provider side

* **Client Sign In URL:** The URL of the providers sign in page linked with our app. Since we have been using the **Altogic Client Library**, we won’t need this URL to redirect to the providers sign in page

We covered the fundamental concepts of the OAuth provider authentication. Let’s move on to the providers’ self configuration on their consoles.

### **Google**

 1. Sign in to your **Google Developer** account

 2. Click on **Create Project**

 3. After creating the project select **OAuth Consent Screen** on the left sidebar

 4. Select user type as **External** and click on **Create** button

 5. Fill in the necessary blanks such as **App Domain, Test Users** , etc.

![OAuth Consent Screen](https://cdn-images-1.medium.com/max/6912/1*exMUDKpVDO124QwO8xTzIQ.png)

 1. After setting up the OAuth Consent Screen, select **Credentials **on the left sidebar

 2. Click on **Create Credentials → OAuth Client ID**

 3. Select application type as **Web Application**

 4. Paste your **Development-Callback URL** to the **Authorized Redirect URIs**

 5. Your **Client ID** and **Client Secret** will be shown in the pop-up after creating the OAuth Client ID or in the right-top of the Credentials tab

 6. Paste **Client ID** and **Client Secret **to the related fields on **Altogic Designer**

![Google Credential](https://cdn-images-1.medium.com/max/2920/1*AMlOvewEkgvdv31G4wjsBQ.png)

You can watch video tutorial of the Configuration of **Google** **OAuth** provider:
{% embed https://www.youtube.com/embed/vfVKjtp7o8M %}
### **Facebook**

 1. Sign in to your **Facebook Developers** account

 2. Click on **Create App** on the right-top of the home page

 3. Select **Consumer**

 4. Set up **Facebook Login** to your app

 5. Select **App Review → Permission and Features** on the left sidebar

 6. **Get advanced access** for the public_profile

 7. Select **Facebook Login → Settings** on the left sidebar

 8. Paste your **Development-Callback URL **to the **Valid OAuth Redirect URIs**

 9. Select **Settings → Basic** on the left sidebar

 10. Copy&paste the **App ID** and **App Secret **to the related fields on **Altogic Designer.**

![Facebook Credetials](https://cdn-images-1.medium.com/max/3200/1*YOyj9WU9ONPb14-Ju5LiNQ.png)

You can watch video tutorial of the Configuration of **Facebook** **OAuth** provider:
{% embed https://www.youtube.com/embed/g84vwxsryZk  %}
### **Twitter**

 1. Sign in to your **Twitter Developer Portal**

 2. Click on **Create Project** in the middle of the home page

 3. Enter the necessary information related(App name, description, etc.)

 4. After creating your project, click **Edit** button on **Authentication Settings** tab

 5. Make sure **3-legged OAuth** and **Request email addresses from users** is selected

 6. Paste your **Development-Callback URL** to the **Callback URLs** field

 7. Type your **Website, Terms of Service, Privacy Policy URLs**

 8. Change tab to the **Keys and Tokens **and **Regenerate Keys**

 9. Copy&paste the **API Key** and **Key Secret** to the related fields on **Altogic Designer.** (Consumer key and consumer secret)

![Twitter Credentials](https://cdn-images-1.medium.com/max/2196/1*t0uoI5n6wYlfFITsmduZFw.png)

You can watch video tutorial of the Configuration of **Twitter** **OAuth** provider:
{% embed https://www.youtube.com/embed/tk1cPCezgRw %}
### **Discord**

 1. Sign in to your **Discord Developers** account

 2. Click on **New Application** on the right bottom of the home page

 3. Give your application a name and click on **Create**

 4. Select **OAuth2** on the left sidebar

 5. Click on **Add Redirect** button

 6. Paste your **Development-Callback URL** in here

 7. Copy&paste the **Client ID** and **Client Secret** to the related fields on **Altogic Designer.**

![Discord Credentials](https://cdn-images-1.medium.com/max/3200/1*EGWHiOFEMIK0LXUxRid25A.png)

You can watch video tutorial of the Configuration of **Discord** **OAuth** provider:
{% embed https://www.youtube.com/embed/e1nFti5ATLs %}
### **Github**

 1. Sign in to your **Github** account.

 2. Open your profile dropdown on the right-top of the page and click **Settings**

 3. Click on **Developer Settings** at the bottom of the Settings page

 4. Select **OAuth Apps** and click on **Register a new application**

![Github Create OAuth App](https://cdn-images-1.medium.com/max/3136/1*3VqGCUaX1osjDgk1v3AUDA.png)

* **Homepage URL:** Our frontend application’s index URL

* **Authorization callback URL:** Auth redirect URL that **Altogic** creates for us

After creating our OAuth app on Github, there will be Client ID and Client Secrets presented in the General tab. Copy&paste them to the related fields on **Altogic Designer.**

![Github Credentials](https://cdn-images-1.medium.com/max/3200/1*1-zYugmgNEFqfxNLpKlIvA.png)

You can watch video tutorial of the Configuration of **Github** **OAuth** provider:
{% embed https://www.youtube.com/embed/qKfdaAur18g %}
## Frontend Development

## Installation

Before installing the application, be sure you have already installed NodeJS in your development environment.

To install
>  💡 You can visit: [https://nodejs.org/en/download/](https://nodejs.org/en/download/) to download.

To get started, open the terminal and create a new React project

    // creates a react app with the name of 'altogic-oauth-provider-authentication-tutorial'
    npx create-react-app altogic-oauth-provider-authentication-tutorial

The above command creates a React project in the altogic-oauth-provider-authentication-tutorialdirectory.

    cd altogic-oauth-provider-authentication-tutorial
    touch .env

Create a `.env` file in the root directory of your application, open the file in your editor and paste the following.
{% gist https://gist.github.com/yasinkuyuk/dea111148c4e219759781deeae842fda.js %}
Replace `YOUR-APPLICATION-ENV-URL` and `YOUR-APPLICATION-CLIENT-KEY` with the `envUrl` and `clientKey` you copied before, then return to your terminal.

Install the Altogic client library to our project by using NPM or Yarn by running the following command:

    // Installation of Altogic Client Library with NPM
    npm i altogic

Next, create a file to handle the **Altogic** services and client.

Go back to your root directory and follow the commands below:

    cd src
    mkdir helpers
    cd helpers
    touch altogic.js

`altogic.js` will be created in the src/helpers directory. Open the file in your editor and paste the following.
{% gist https://gist.github.com/yasinkuyuk/78de2411385c22fa649e37d85f183bc7.js %}
The third parameter of **createClient** function `signInRedirect` handles the redirection to the Sign In page automatically when you have invalid session tokens or signed out. This is a beneficial feature for managing sessions in scenarios when you sign out from your mobile phone.

### User Interface Components

We will use **Tailwind CSS** and **Headless UI** library for styling the project. Run the following commands in the root directory to install the library.

    npm install -D tailwindcss postcss autoprefixer
    npm install @headlessui/react

Below command will create `tailwind.config.js` file:

    npx tailwindcss init -p

Open the `tailwind.config.js` in editor and copy/paste following script to configure template paths:
{% gist https://gist.github.com/yasinkuyuk/2329374575bc3a9964cbb01b39de5deb.js %}
Open index.css file in src directory and add the following directives:
{% gist https://gist.github.com/yasinkuyuk/d2c05716eb78384ab4643da3fead84d8.js %}
And we will use Font Awesome Icons in our project. You should install the Font Awesome Library to have well-looking components.

1. Add SVG Core:

    npm i --save @fortawesome/fontawesome-svg-core

2. Add Icon Packages:

    npm i --save @fortawesome/free-solid-svg-icons
    npm i --save @fortawesome/free-regular-svg-icons
    npm i --save @fortawesome/free-brands-svg-icons

3. Add React Component

    npm i --save @fortawesome/react-fontawesome@latest

We installed the necessary dependencies to our project for styling. Now, it is time to install react-router for routing our Single Page Application(SPA).

    npm i react-router-dom

We completed the installation part of the project. We will use custom button components to style our application. Open your terminal on your root directory and type following commands one by one:

    cd src
    mkdir components
    cd components
    mkdir Buttons
    cd Buttons
    touch PrimaryButton.js SecondaryButton.js

Above commands will create `PrimaryButton` and `SecondaryButton` files under `/src/components/Buttons `directory. Now, you can copy&paste the following scripts to the related files:
{% gist https://gist.github.com/yasinkuyuk/202410096297e8d268b71dee55a204a8.js %}{% gist https://gist.github.com/yasinkuyuk/5b91e0ba90f04dfc50ef95895a3374c3.js %}
## Implementation

### Building Main Components

The next step is to create the core components that we’ll need for our application,

 1. `ProviderSelector` A component that can be used for redirection to the provider both sign in and sign up

 2. `AuthRedirect` A component that the user is redirected to after the provider’s authorization

 3. `App` The main application component. It renders all the views with their properties.

Switch to the root directory of your react application and run following commands:

    cd src
    mkdir pages
    cd pages
    touch AuthRedirect.js ProviderSelector.js

This creates a pages directory with the components in the src directory. Your folder structure should look similar to the screenshot:

![](https://cdn-images-1.medium.com/max/2000/1*xC28rfr8FYMNlsQgOQyrgg.png)

Since the user must be redirected to the related providers authorization page, we will develop the `ProviderSelector` component.

**Altogic Client Library** has just one simple method to handle both sign up and sign in cases to simplify the authentication process. A user instance is created in the database right after the first sign in/up action with the application. Therefore; I don’t have to design multiple use cases as a developer. Thus, we will handle sign in and sign up functionalities within just one component. We will be adding two different routes such as _/signin_ and _/signup_, however same component will be rendered inside them with different texts.

We will design 5 buttons for each provider: **Google, Facebook, Twitter, Github, Discord.** When the user clicks the related button, it triggers the `signin(provider)` function defined inside the component. We will call **Altogic Client Library** `altogic.auth.signInWithProvider(provider)` method to redirect the user to the related authorization page.
{% gist https://gist.github.com/yasinkuyuk/05c9a7830208a794ea86d63a12d20006.js %}
![](https://cdn-images-1.medium.com/max/2124/1*7gc-Tfr2WmURt7ZmKWTC1A.png)

As we early noticed in the article, users will be redirected to the frontend of the application with specific routing. We have to catch the return response of the redirection URL and take necessary actions on the application such as setting `isAuth` state in the context.

Now, we will develop a viewless `AuthRedirect` component to handle access_token from the provider and check whether the user is authenticated or somehow not.
{% gist https://gist.github.com/yasinkuyuk/cb17b06b14238e2add4e510598ed690d.js %}
**BONUS: Extra Features/Components**

To focus on the main purpose of the article, we won’t go over with the development of the below components in this article. However, you can reach the source code of the extra feature components from [Github repository](https://github.com/altogic/altogic/tree/main/examples/react-oauth-provider-authentication) for full-featured app.

 1. `Profile` A component that the users can view, upload and remove their profile pictures

 2. `Sessions` A component that the users can view and sign out from their active sessions. Built with SessionTable and SessionItem sub-components.

 3. `Footer` ,`Header` ,`ProfileDropdown` Navigation bar and footer badge

 4. `NotFound` A component to catch the routes not presented in application routes

 5. `Notification` A component that notifies the user about requests/responses

 6. `RequiresAuth` A wrapper component that checks whether the user is authenticated before rendering a component; otherwise, it redirects the user to the signup/login page.

 7. `RequiresNotAuth` A wrapper component that checks whether the user is not authenticated before rendering a component; otherwise, it redirects the user back to the profile page(for example Sign In page).

 8. `ModalContext` , ModalProvider Provides context structure to communicate between components to show notifications to the user

You can see the list of related **Altogic** functions with above features:
{% gist https://gist.github.com/yasinkuyuk/53e34c833671eb9b2ad7f17179ceeaad.js %}
**Authentication Context**

Here we came to the one of the core component and structure of app, `AuthenticationContext` created using `useContext()` hook. Context is used to generate shared data accessible across the component hierarchy without passing props to each component. For example, `isAuth` state stores the boolean value of is user authenticated or not. Almost every component must use the isAuth state to handle its internal functionalities. I could pass props to each component like parent to child. However it is not flexible and easy to use. I built an `AuthenticationContext` to handle and manage all the data and functionalities related with authentication.

I defined all my Altogic functions and related states in `AuthenticationContext` to distribute it to the child components.
{% gist https://gist.github.com/yasinkuyuk/7dc13d60279093ad37d0fdd6cf449795.js %}
Finally, we have completed the implementation of the core components of our application. It only remains the development of the App component left. You can reach the source code of the additional side components from the [Github repository.](https://github.com/altogic/altogic/tree/main/examples/react-oauth-provider-authentication)

We defined the routes in the App component. Routes are protected with `RequiresAuth` and `RequiresNotAuth` restriction components.
{% gist https://gist.github.com/yasink7/c5cc431ff2dea89479fec6272645877d.js %}
Open the terminal in the root directory and paste the following command to run your application:

    npm run start

## **Conclusion**

In this tutorial, we walked through how to configure OAuth Provider Authentication in [React](https://reactjs.org/) app using **Altogic** and [Tailwind CSS.](https://tailwindcss.com/docs/guides/create-react-app) We all covered detailed configuration of **Google, Facebook, Twitter, Discord** and **Github** providers in our **Altogic** app. If you build your backend application with coding in pure programming languages & frameworks; the configuration process will take your time and effort. However, with the significant help of the **Altogic, **we implement only 10 lines of code snippet inside the `ProviderSelector`, `AuthRedirect` components.

Check out the [Github repository](https://github.com/altogic/altogic/tree/main/examples/react-oauth-provider-authentication) for the source code of the application for further details.