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

2024-03-26

我已经用 ReactJs 设置了 github 的 Electron。所以我得到了一个BrowserWindow一个 React 应用程序在该窗口中运行得很好。我想要实现的是通过 GitHub 进行身份验证。所以当用户按下Login with Github按钮,一个新的BrowserWindow打开并转到 github 授权应用程序 url。我遇到的问题与callback以及我将如何获取从回调返回的代码。我已经用 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.");
  }
});

我在哪里做console.log(JSON.stringify(stream)); I get {}所以这是必须做的事情eventListener?有什么想法或更好的方法吗?


所以我缺少的是正确的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);

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Electron & ReactJS,使用 BrowserWindow 进行 GitHub oAuth 身份验证 的相关文章

随机推荐