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

mar*_*tch 15 javascript oauth-2.0 electron

这主要是缺乏对oauth2的理解,可能并不特定于电子,但是我试图解决一个人如何处理桌面平台上的oauth2重定向网址,比如电子?

假设没有Web服务设置作为应用程序的一部分,桌面应用程序将如何提示用户提供针对第三方oauth2服务的凭据,然后正确地对其进行身份验证?

rya*_*yer 18

Electron JS在您的localhost上运行浏览器实例.因此,您可以通过提供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;
});
Run Code Online (Sandbox Code Playgroud)

从这个页面获取了很多灵感:http://manos.im/blog/electron-oauth-with-github/

  • 我正在使用Electron进行Spotify的身份验证.为此,我需要在`authUrl`中传递重定向URI.如果不使用Node.js的"express"模块来定义路径,我怎么能使用像`https:// localhost/callback`之类的东西? (2认同)
  • 您能否澄清“电子 js 在您的本地主机上运行浏览器实例”的意思?当电子应用程序被打包用于生产时,情况并非如此。如您所见,这是我从 keycloak 得到的错误 - 请注意,redirect_uri 不再是有效的 uri,而是引用了 index.html 文件.. WARN [org.keycloak.events](默认任务-4)type=LOGIN_ERROR,realmId=codingpedia,clientId=invoices-ui,userId=null,ipAddress=127.0.0.1,error=invalid_redirect_uri,redirect_uri=file:///tmp/.mount_react-myxJe9/resources/app.asar /build/index.html (2认同)

Lou*_*med 5

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