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



这主要是对oauth2缺乏了解,可能不是特定于电子的,但是我试图弄清楚有人如何处理来自桌面平台的oauth2重定向URL,例如电子?

假设应用没有 Web 服务设置,桌面应用程序将如何提示用户输入针对第三方 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/

感谢您提供此解决方案。我还注意到,当浏览器窗口没有单击触发重定向到应用程序重定向 uri 时,来自 webContent 的导航事件是不可靠的。例如,如果我已经在浏览器窗口中登录,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
  });
});

相关内容

最新更新