Securing Electron app with Keycloak

2019-08-29 06:07发布

I'm new to Keycloak and having a hard time authenticating a desktop app written on Electron. I looked at the documentation that discusses the OpenID Connect endpoint and then found a blog that walks through Keycloak and Postman and I was able to get tokens from Keycloak via this method.

I'm pretty sure this is incorrect for a few reasons.

How can I authenticate my Electron app without running a client side web server to handle the redirects? There is an example for authenticating a web app, but does anyone have a simple example of how to authenticate an Electron app against Keycloak?

2条回答
不美不萌又怎样
2楼-- · 2019-08-29 06:33

Finally, I've managed to implement Keycloak authentication with Electron app. The thing is to fork a temporary http server from the main process of your app. This server should listen to a redirect request after successful Keycloak login. Of course, for this to work you should specify the address of this server in the *Valid Redirect URIs input of your Keycloak client, say http://localhost:33333. When the request comes to the server, you parse it and extract the 'search' part of the request. Then you append this 'search' part to your index.html path and load mainWindow from it:

const url = `file://${path.join(__dirname, '../index.html')}${searchString}`;
mainWindow.loadURL(url);

Works good for me.

PS. I can elaborate on this solution with sample code upon request.

查看更多
可以哭但决不认输i
3楼-- · 2019-08-29 06:34
  import Keycloak from 'keycloak-js';

  if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
    // don't need keycloak in development mode, change the condition to if (false) to force keycloak to be required locally
  } else {
    keycloak.init({ onLoad: 'login-required', checkLoginIframeInterval: 1 }).success((authenticated) => {
      if (authenticated) {
        sessionStorage.setItem('kctoken', keycloak.token);

        setInterval(() => {
          keycloak.updateToken(10).error(() => keycloak.logout());
          sessionStorage.setItem('kctoken', keycloak.token);
        }, 10000);
      } else {
        keycloak.login();
      }
    });
  }

Try that and post back thanks :)

查看更多
登录 后发表回答