Social Login with React, Rails API, Devise Auth Token

Muwonge Nicholus
2 min readOct 25, 2020
Photo by Brett Jordan on Unsplash

Just the other week, I was faced with a challenge to implement social auth using Omniauth. It seems to me, it wasn't well optimized for APIs and this could cause you some good headache. Here’s a little demonstration of how you could approach it.

The first challenge is always figuring the data flow to login someone here it goes;

  • In React you invoke a request by clicking a button which fires off a request to the provider (Facebook or Google or whatever). This is usually where you have attached a client ID to the request.
  • The client returns you a response with the details, an access token and a user id.
  • This is what you send to the back end to pick out the user details and save the user or log them in and send a message and an access-token through the callback.

Let’s start with the Front end in React.js

App.js

So when that's all done, we expect data from the backend in the form of a response from the API.

We need to add Omniauth to our application by adding these gems to the Gemfile and running bundle install

Gemfile

Set up the providers after getting the credentials from either Google developers console or Facebook console

Devise setup

I'm assuming you already have a user model in place so place this code in there

User Model

So we also set up the CORS and add this other code to allow Devise omniauth to work perfectly with APIs.

Setup CORS and Devise Omniauth for APIs

Let's go ahead and add a controller where all this logic that I stated up will be handled

Controller

To finish it all off, let's add a call back URL that will be called in React in which we shall be sending information about the user login.

Don't forget to add rack-cors a gem for the CORS to the Gemfile and run bundle i .

To test it all out, get the route we just created and paste in as the callback URL in react and make a request. Make sure both servers are started and running.

Hope this helps and if you have questions please leave me a comment. I will get back to you soonest as I can.

Cheers!!!

--

--

Muwonge Nicholus

I am a Javascript and Ruby engineer. I love designing user interfaces and currently working in payment systems.