处理来自电子(或其他桌面平台)的 oauth2 重定向

Handling oauth2 redirect from electron (or other desktop platforms)

这主要是缺乏对 oauth2 的理解,可能不是特定于 electron,但是我正在努力思考某人如何处理来自桌面平台的 oauth2 重定向 url,例如 electron ?

假设没有网络服务设置作为应用程序的一部分,桌面应用程序将如何提示用户输入针对第三方 oauth2 服务的凭据,然后正确验证他们?

Electron JS 在您的本地主机上运行一个浏览器实例。因此,您可以通过提供 https:localhost/whatever/path/you/want 的回调 url 来处理 oauth2 重定向 url。无论您使用什么服务,请务必在 oauth2 应用程序注册页面上将其列入白名单。

示例:

var authWindow = new BrowserWindow({
    width: 800, 
    height: 600, 
    show: false, 
    'node-integration': false,
    'web-security': false
});
// This is just an example url - follow the guide for whatever service you are using
var authUrl = 'https://SOMEAPI.com/authorize?{client_secret}....'

authWindow.loadURL(authUrl);
authWindow.show();
// 'will-navigate' is an event emitted when the window.location changes
// newUrl should contain the tokens you need
authWindow.webContents.on('will-navigate', function (event, newUrl) {
    console.log(newUrl);
    // More complex code to handle tokens goes here
});

authWindow.on('closed', function() {
    authWindow = null;
});

很多灵感来自此页面:http://manos.im/blog/electron-oauth-with-github/

感谢您提供此解决方案。我还注意到,当没有点击浏览器 window 触发重定向到应用程序重定向 uri 时,来自 webContents 的导航事件不可靠。例如,如果我已经在浏览器 window 中登录,Github 登录页面将永远不会使用重定向 URI 触发此事件。 (它可能使用了一些会话存储)。

我找到的解决方法是改用 WebRequest

const { session } = require('electron');

// my application redirect uri
const redirectUri = 'http://localhost/oauth/redirect'

// Prepare to filter only the callbacks for my redirectUri
const filter = {
  urls: [redirectUri + '*']
};

// intercept all the requests for that includes my redirect uri
session.defaultSession.webRequest.onBeforeRequest(filter, function (details, callback) {
  const url = details.url;
  // process the callback url and get any param you need

  // don't forget to let the request proceed
  callback({
    cancel: false
  });
});