JoseGoncalves / vue-keycloak

Keycloak plugin for Vue 3 with Composition API
Apache License 2.0
20 stars 6 forks source link

Add Support for keycloak callback listeners #12

Closed joema-ww closed 1 month ago

joema-ww commented 1 month ago
// Sample usage.
const app = createApp(App)

app.use(vueKeycloak, {
  config: {
    url: 'http://keycloak-server/auth',
    realm: 'my-realm',
    clientId: 'my-app',
  },
  initOptions: {
    onLoad: 'check-sso'
  },
  // New configuration for the callback listeners.
  callback: {
    onAuthSuccess: () => { console.log('authenticated') },
    onAuthLogout: () => { console.log('user is logged out') }
  }
})
JoseGoncalves commented 1 month ago

Hi @joema-ww. Don't see the need to add code to support that, because you can use a watch on the keycloak reactive instance to setup the callbacks. Something like the following should work:

<script setup>
import { watch } from 'vue';
import { useKeycloak } from '@josempgon/vue-keycloak';

const { keycloak } = useKeycloak();

watch(
    keycloak,
    value => {
        if (value) setKeycloakCallbacks(value);
    },
    { immediate: true },
);

function setKeycloakCallbacks(kc) {
    kc.onReady = authenticated => console.log('onReady:', authenticated);
    kc.onAuthSuccess = () => console.log('onAuthSuccess');
    kc.onAuthError = errorData => console.log('onAuthError:', errorData);
    kc.onAuthRefreshSuccess = () => console.log('onAuthRefreshSuccess');
    kc.onAuthRefreshError = () => console.log('onAuthRefreshError');
    kc.onAuthLogout = () => console.log('onAuthLogout');
    kc.onTokenExpired = () => console.log('onTokenExpired');
}
</script>
joema-ww commented 1 month ago

Great, everything is working as expected now! Thanks so much for sharing the solution. I'll close the issue.