Electron&ReactJS,使用BrowserWindow进行GitHub oAuth身份验证

man*_*sim 4 oauth callback github-api electron

我用ReactJs设置了github的Electron.所以我得到了一个BrowserWindow和一个反应应用程序在那个窗口很好地播放.我想要实现的是通过GitHub进行身份验证.因此,当用户按下Login with Github按钮时,会BrowserWindow打开一个新的并转到github授权应用程序URL.我的问题与回调有关,以及我将如何从回调中返回代码.我已经用Apache Cordova完成了它,InAppBrowser但它因为我能够localhost用作回调而有所不同.

到目前为止我用电子做的是打开新的,BrowserWindow但在授权后我无法从回调中获取代码.

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.");
  }
});
Run Code Online (Sandbox Code Playgroud)

我正在做的事情console.log(JSON.stringify(stream));我得到了{}这样的东西必须做的事情eventListener?任何想法或更好的方法?

man*_*sim 5

所以我错过的是正确的event.正确的方法是:

// Build the OAuth consent page URL
var authWindow = new BrowserWindow({ width: 800, height: 600, show: false, 'node-integration': false });
var githubUrl = 'https://github.com/login/oauth/authorize?';
var authUrl = githubUrl + 'client_id=' + options.client_id + '&scope=' + options.scopes;
authWindow.loadUrl(authUrl);
authWindow.show();

// Handle the response from GitHub
authWindow.webContents.on('did-get-redirect-request', function(event, oldUrl, newUrl) {

  var raw_code = /code=([^&]*)/.exec(newUrl) || null,
    code = (raw_code && raw_code.length > 1) ? raw_code[1] : null,
    error = /\?error=(.+)$/.exec(newUrl);

  if (code || error) {
    // Close the browser if code found or error
    authWindow.close();
  }

  // If there is a code in the callback, proceed to get token from github
  if (code) {
    requestGithubToken(options, code);
  } else if (error) {
    alert("Oops! Something went wrong and we couldn't log you in using Github. Please try again.");
  }

});

// Reset the authWindow on close
authWindow.on('close', function() {
    authWindow = null;
}, false);
Run Code Online (Sandbox Code Playgroud)

我还写了一个描述完整实现的教程,可以在http://manos.im/blog/electron-oauth-with-github/找到.