Skip to content

Instantly share code, notes, and snippets.

@sairamkrish
Last active June 23, 2022 02:39
Show Gist options
  • Save sairamkrish/2bd5c97470d392b715682e6113171c40 to your computer and use it in GitHub Desktop.
Save sairamkrish/2bd5c97470d392b715682e6113171c40 to your computer and use it in GitHub Desktop.
Vue JS integration with keycloak
import Keycloak from 'keycloak-js';
...
const keycloakConfig = {
"url": "/auth",
"realm": "your-realm-name",
"clientId": "vue_frontend",
"onLoad": "login-required"
};
const keycloak = Keycloak(keycloakConfig);
keycloak.init({ onLoad: keycloakConfig.onLoad }).success((auth) =>{
if(!auth) {
window.location.reload();
} else {
console.log("Authenticated");
}
new Vue({
render: h => h(App),
}).$mount('#app');
localStorage.setItem("vue-token", keycloak.token);
localStorage.setItem("vue-refresh-token", keycloak.refreshToken);
// To fetch UserInfo like name, email id etc.,
keycloak.loadUserInfo().success(userInfo => {
localStorage.setItem('userInfo', JSON.stringify(userInfo));
}
//Every 60 second check if token expires soon (here 70 seconds used in updateToken), if so, refresh it.
setInterval(() =>{
// updateToken parameter is the minValidaty time
keycloak.updateToken(70).success((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');
}
}).error(()=>{
console.log('Failed to refresh token');
});
}, 60000)
}).error(() =>{
console.log("Authenticated Failed");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment