Electron & ReactJS, Use BrowserWindow for GitHub oAuth authentication


#1

I have set up github’s Electron with ReactJs. So I got a BrowserWindow and a react app playing nicely in that window. What I’m trying to achieve is to get authenticated with GitHub. So when a user presses the Login with Github button, a new BrowserWindow opens and goes to the github authorize app url. The issue I have has to do with the callback and how I will get the code returned from the callback. I’ve done it with Apache Cordova and the InAppBrowser but it was different since I was able to use localhost as a callback.

What I’ve done so far with electron is opening the new BrowserWindow but after the authorization I cannot get the code from the callback.

var authWindow = new BrowserWindow({ width: 800, height: 600, show: true, 'always-on-top': true });
var githubUrl = 'https://github.com/login/oauth/authorize?';
var authUrl = githubUrl + 'client_id=' + options.client_id + '&scope=' + options.scope;

authWindow.loadUrl(authUrl);
authWindow.setVisibleOnAllWorkspaces(true);
authWindow.setResizable(false);

authWindow.addListener('page-title-updated', function(stream) {
  console.log("LOADED");
  console.log(JSON.stringify(stream));
  console.log(stream);

  var url = (typeof stream.url !== 'undefined' ? stream.url : stream.originalEvent.url),
    raw_code = /code=([^&]*)/.exec(stream.url) || null,
    code = (raw_code && raw_code.length > 1) ? raw_code[1] : null,
    error = /\?error=(.+)$/.exec(strean.url);

  if (code || error) {
    authWindow.close();
  }

  // If there is a code in the callback, proceed to get token from github
  if (code) {
    // requestToken(code);
  } else if (error) {
    alert("Oops! Couldn't log authenticate you with using Github.");
  }
});

Where I’m doing console.log(JSON.stringify(stream)); I get {} so it’s something that has to do with the eventListener’s event (I guess I need something like location-load? Any ideas or better approaches?


#2

For others coming across this thread trying to do the same thing (I was!) it looks like ekonstantinidis has posted a full solution on his blog here: http://iamemmanouil.com/blog/electron-oauth-with-github/

Thanks ekonstantinidis!