Using keycloak-js for authenticating my vue.js application, I have implemented the following code in my main.js
file. This snippet was taken from :
import { store } from "./store/store";
let keycloak = Keycloak(initOptions);
keycloak.init({ onLoad: initOptions.onLoad }).then((auth) => {
if (!auth) {
window.location.reload();
} else {
console.log("Authenticated");
new Vue({
vuetify, router, store,
render: h => h(App, { props: { keycloak: keycloak } })
}).$mount('#app')
}
const decoded = VueJwtDecode.decode(keycloak.token)
const roles = decoded.realm_access.roles
store.commit("storeRoles", roles)
//Token Refresh
setInterval(() => {
if(store.state.userData.logged_out) { ### done in vuex
keycloak.logout()
} else {
keycloak.updateToken(70).then((refreshed) => {
if (refreshed) {
console.log('Token refreshed' + refreshed);
} else {
console.log('Token not refreshed, valid for '
+ Math.round(keycloak.tokenParsed.exp + keycloak.timeSkew - new Date().getTime() / 1000) + ' seconds');
}
}).catch(() => {
console.log('Failed to refresh token');
});
}
}, 2000)
}).catch(() => {
console.log("Authenticated Failed");
});
In order to handle this process through a button click, I'm currently committing a mutation in my Vuex store.
if(store.state.userData.logged_out) { ### done in vuex
keycloak.logout()
}
## Triggered by clicking a button in my view
this.$store.commit("logout", true)
The current approach feels a bit cumbersome as there is a 2-second delay before the user is logged out. Is there a more direct way to access the keycloak instance from a component?