Social login with React and Django — II

React implementation to get the access token for Facebook and Google

Pratik Singh Chauhan
3 min readJun 14, 2020

In the previous part of this tutorial we hosted an API based Django backend using django-rest-framework to handle social authentication for Facebook and Google, this part aims at creating frontend using react. So let’s get started by creating a react app using create react app, run the command

npx create-react-app react_auth

The official react website can be followed for the initial project setup. For the authentication, we will use npm libraries react-facebook-login and react-google-login. The libraries can be installed from npm using,

npm i react-facebook-login
npm i react-google-login

We will create a component that will render the login buttons. In the following code add the appId and clientId for Facebook and Google respectively, this component will log the user in and will print the information of logged in user on the browser console including the access token.

This code will render login buttons to the UI as below, clicking these buttons should open the login popup, which would return the access token on success, that has to be sent to the API we created in the first part of this tutorial in order to complete the login/signup process.

Facebook login button
Google Login button

Once done we will post the access token to the backend, for this we use the axios library which can be installed from npm by the following command

npm i axios

Once done we will grab this access token and post it to the backend using the following method,

Now enable Cross-origin resource sharing (CORS) in our Django API so we can serve requests from other domains, for that we install django-cors-headers to our application,

pip install django-cors-headers

To the INSTALLED_APPSin settings.py we add,

INSTALLED_APPS = [
...
'corsheaders',
...
]

You will also need to add middleware in settings.py to listen to requests.

MIDDLEWARE = [  
...
'corsheaders.middleware.CorsMiddleware',
...
]

To whitelist all domains we can add the following line at the end of settings.py. Alternatively, we can whitelist specific domains,

CORS_ORIGIN_ALLOW_ALL = True

Once this is done, our application is ready to authenticate users and save their information to the database. Similarly, other social media applications can be added, have a look at this documentation for a list of all the apps supported by the library. The complete code for this tutorial can be found in this GitHub repository.

Next, steps can be to redirect the user to the homepage once the authentication is completed, also registration and login using username and password may be added to the application. Thanks for reading and stay tuned for more content.

--

--

Pratik Singh Chauhan
Pratik Singh Chauhan

Written by Pratik Singh Chauhan

My opinions are my own. Software Developer at heart.

Responses (9)