Keep authentication between 2 applications with Keycloak SSO

|▌冷眼眸甩不掉的悲伤 提交于 2020-06-18 04:33:30

问题


I have 2 JHipster apps running each on one subdomain (app1.domain.tld & app2.domain.tld).

In both apps, users login through Keycloak. The sequence is as such :

  1. Angular app sends /authenticate request with credentials to Keycloak
  2. In case of successful response returns a authentication cookie
  3. POST request is is sent to Jhipster backend app that generates JSessionID cookie
  4. JSessionID is then used for every request to backed app.

What would be the best way to automatically login user (without asking username & password) if they are already logged in one of the apps of the domain (*.domain.tld) ?

I tried to use the JSessionID as a global token before understanding it only works on the app it was generated on...

Maybe catching Keycloak authentication cookie (returned at step 2) and authenticating on second application would do the trick ?

From what I saw while testing, after being authenticated on first app, when I go to the second one, Angular 401 HTTP interceptor redirects to keycloak login page with a session token. Thus at that time Keycloak should see that I'm already logged in and should redirect me to home page of my second app.

Am I right ?


回答1:


The javascript adapter solve this by creating an iframe that's loaded from the authentication server.

From the keycloak docs:

Session Status iframe

By default, the JavaScript adapter creates a hidden iframe that is used to detect if a Single-Sign Out has occurred. This does not require any network traffic, instead the status is retrieved by looking at a special status cookie. This feature can be disabled by setting checkLoginIframe: false in the options passed to the init method.You should not rely on looking at this cookie directly. Its format can change and it’s also associated with the URL of the Keycloak server, not your application.

The success callback of init function has a parameter that gives the authentication status of the user.

<script src="keycloak.js"></script>
<script>
    var keycloak = Keycloak();
    keycloak.init().success(function(authenticated) {
        alert(authenticated ? 'authenticated' : 'not authenticated');
    }).error(function() {
        alert('failed to initialize');
    });
</script>

If the user is authenticated redirect the user to the login page, since the user is already authenticated there is no need to input the login credentials again. The adapter can handle this automatically if it's initialized with the onload option check-sso

For more details on the inner workings of the javascript adapter, the source can be found here



来源:https://stackoverflow.com/questions/53839769/keep-authentication-between-2-applications-with-keycloak-sso

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