Google+Facebook Authorization in React+Redux App

Image for post
Image for post

With Every App Comes Authorization

Broken Hope: AWS Cognito

Image for post
Image for post
https://pomodoro.increaser.org

Introduction

Authentication flow will look this way:

  1. Receive a token from Google/Facebook.
  2. Make a request to the back-end to receive JWT token.
  3. Save token to local storage and use it in requests to back-end until it expires.

Front-end

When a user clicks on one of the buttons appropriate saga will be triggered. Both of them are very similar and have the same steps.

First, we need to load the script if not loaded. We will write the function to do this.

When a provider’s code in place we are calling one of its methods for authorization and pass scope that specifies what user’s data we want, in our case it is email and basic user info.

And of course, we need to get keys to make requests to Google and Facebook and specify them in constants.

With a token from the provider, we are ready to make the request to our app and authorize a user.

In this function, we build a query for GraphQL backend where we specify the name of provider and token. Then we trigger action to save response in the state.

We can save token to local storage in redux middleware like this.

By taking a token from local storage, we can make a request to the API.

I think we covered the main parts of the authorization process on front-end. Now let’s look at what is going on on the back-end.

Back-end

First, let’s write a function that will receive the name of the provider and token and return user and auth data. Also, this function will save user to the database if no such user exists.

Here we are using quite a few utility functions for authorization. Let’s list them here.

To provide userId to the context of a request, we will take a token from headers, validate it and take userId from it.

For Medium readers, I provide a Udemy course How to Start React Project: Best Practices for 9.99$. The goal of this course is to share with You my findings of the last few years about what steps and decisions are better to make at the beginning of development so that you will have a good starting point for your new project.

Reach the next level of focus and productivity with increaser.org.

Image for post
Image for post
Increaser

Written by

Software engineer, creator of increaser.org. More at geekrodion.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store