2,668 Views

Lets make a facebook login system in electron that actually works

I tried two days trying to implement facebook login in my electron application. I went through lots of forums and lots of documentation. After much searching and combining what I found in multiple articles and forums answers, I made it to work. So I thought I should share how I implemented facebook login in my electron application.

If don’t know about electron or just starting, this tutorial may not be for you. But if you know just the basics of electron and javascript, then you can easily follow through. To learn more about electron visit electron.atom.io.

Create an Electron hello world app

To begin, let’s clone the starter templated by electron developers themselves
git clone https://github.com/electron/electron-quick-start.git
This should clone the repository. Let’s just rename the project directory to electron-facebook.
Let’s cd into the electron-facebook directory and run yarn install (If you don’t know what yarn is or don’t have yarn already, it’s a wonderful replacement for npm. visit https://yarnpkg.com for more details.)

This should install the dependencies required, which in this case is only one electron.
Once the dependencies are install just run yarn start and this should run electron hello world program.

So let’s begin what we are here to do, implement facebook authentication system in electron based desktop applications.

Install dependencies for facebook authentication with electron

While in your project root directory in your terminal run
yarn add fb
This should add NodeJS Library for facebook. We will use this later to access facebook api.

Prepare use interface

Let’s add a button to allow user to Login with facebook and some other tags to display user’s profile after login is completed successfully.
Open index.html and replace the body of the html file with following code

<script type="text/javascript">
 const {ipcRenderer} = require('electron')
 var loginWithFB = function () {
 ipcRenderer.send("fb-authenticate", "yes");
 };
</script>
 <button id="fb-button" onclick="loginWithFB();">Sign in with Facebook</button><br><br>
 <table>
 <tr>
 <td rowspan="2" style='width:128px;height:128px;'><img src="img/avatar.jpg" id="fb-pp"></img></td>
 <td id="fb-name"></td>
 </tr>
 <tr>
 <td id="fb-id"></td>
 </tr>
 </table>

Nothing fancy here, requiring electron IpcRenderer to send message from renderer process to main process. A button showing login with facebook,when user clicks, message is sent to the main process to authenticate with facebook. A table with bunch of rows and columns to show user profile name, id and picture if login is successful.

Create and setup facebook developers app

  1. Goto https://developers.facebook.com and if you have not already logged in, login.
  2. On the top right, there is a menu called My Apps, hover over My Apps and you will see the list of apps you host, also there is an option Add a New App below the list of your apps, click on Add a new App
    ele1_1.png
  3. You then will be provided with a new App dialog, fill in the dialog and click on the “Create App ID” button. You can use the display name, contact email and category of your desire.
    ele1_3.png
  4. Confirm the security check in the next dialog, solving the provided Captcha.
  5. If everything goes well, you will be redirected to your newly created apps Product Setup Page. And at the top left corner you can see your App ID. We will need that in next step.
    ele1_4.png
  6. At this page, choose, Facebook Login and click get started button at the right side of the option
  7. You will see the Choose platform, however we do not want any platform, we want to build login flow manually, so skip this, on the left sidebar click on Settings submenu of facebook login and you will see the as in the following image
    ele1_5.png
  8. In the Valid OAuth Uri field add the following https://www.facebook.com/connect/login_success.html and click save changes button at the bottom right.

And that’s done

Prepare main process, the actual authentication process

Open your main.js file and at the end add the following codes

const ipcMain = electron.ipcMain;
var FB = require('fb');
ipcMain.on("fb-authenticate",function (event, arg) {
    var options = {
      client_id: '',
      scopes: "public_profile",
      redirect_uri: "https://www.facebook.com/connect/login_success.html"
    };
    var authWindow = new BrowserWindow({ width: 450, height: 300, show: false,
      parent: mainWindow, modal: true, webPreferences: {nodeIntegration:false} });
    var facebookAuthURL = "https://www.facebook.com/v2.8/dialog/oauth?client_id=" + options.client_id + "&redirect_uri=" + options.redirect_uri + "&response_type=token,granted_scopes&scope=" + options.scopes + "&display=popup";
    authWindow.loadURL(facebookAuthURL);
    authWindow.show();
    authWindow.webContents.on('did-get-redirect-request', function (event, oldUrl, newUrl) {
      var raw_code = /access_token=([^&]*)/.exec(newUrl) || null;
      var access_token = (raw_code && raw_code.length > 1) ? raw_code[1] : null;
      var error = /\?error=(.+)$/.exec(newUrl);

      if(access_token) {
        FB.setAccessToken(access_token);
        FB.api('/me', { fields: ['id', 'name', 'picture.width(800).height(800)'] }, function (res) {
          mainWindow.webContents.executeJavaScript("document.getElementById(\"fb-name\").innerHTML = \" Name: " + res.name + "\"");
          mainWindow.webContents.executeJavaScript("document.getElementById(\"fb-id\").innerHTML = \" ID: " + res.id + "\"");
          mainWindow.webContents.executeJavaScript("document.getElementById(\"fb-pp\").src = \"" + res.picture.data.url + "\"");
        });
        authWindow.close();
      }
    });
  });

In this part, we are manually building the facebook login progress as discussed here in facebooks documentation.

In place of place the App ID of the app you created in previous step.

See how it works

Now, launch your electron app using yarn start command at your project root from terminal.

You will see the following window
ele1_6.png
Click on the Sign in With Facebook button and following window should popup
ele1_7.png
Login with your username and password and you will see the authentication screen as follows
ele1_8.png
Once you click continue, the popup window should close, and you should see your info being loaded in the main window as follows
ele1_9.png

That’s it, this is the facebook login system implemented in electron, that actually works.
Please provide us with comments on what do you think.

References that helped me implement this login system

Related Posts

%d bloggers like this: