Handling oauth2 redirect from electron (or other desktop platforms)

孤者浪人 提交于 2020-12-27 08:30:50

问题


This is mostly a lack of understanding of oauth2 and probably not specific to electron, however I'm trying to wrap my head around how someone would handle an oauth2 redirect url from a desktop platform, like electron?

Assuming there is no webservice setup as part of the app, how would a desktop application prompt a user for credentials against a third party oauth2 service, and then authenticate them correctly?


回答1:


Electron JS runs a browser instance on your localhost. Therefore, you can handle an oauth2 redirect url by supplying a callback url of https:localhost/whatever/path/you/want. Just be sure to white list it on the oauth2 app registration page for whatever service you are using.

Example:

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;
});

A lot of inspiration taken from this page: http://manos.im/blog/electron-oauth-with-github/




回答2:


Thank you for this solution. I also noticed that the navigate events from the webContents are not reliable when no clicks on the browser window triggers the redirection to the application redirect uri. For example Github login page would never trigger this event with the redirect URI if I was already logged in in the browser window. (It was probably using some session storage).

The workaround I found was to use WebRequest instead

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
  });
});


来源:https://stackoverflow.com/questions/37546656/handling-oauth2-redirect-from-electron-or-other-desktop-platforms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!