import Keycloak from 'keycloak-js';
mounted() {
const vm=this;
const keycloak = new Keycloak({
url: '', // 这里需要写你链接的地址
realm: '', // 链接的领域
clientId: '' , // 链接的客户端
})
keycloak.init({onLoad:'login-required',CheckLoginIframe:false}).then((auth)=>{
if(!auth){
window.location.reload()
} else {
// console.log(keycloak)
keycloak.loadUserProfile().then((profile)=>{
this.$store.commit('setUserName',profile.username);//存储用户名
})
this.$store.commit('setKeycloakList',keycloak); //存储keycloak
this.$store.commit('setOdataHeaders',keycloak.token); //存储token
localStorage.setItem('token', keycloak.token) //存储token
}
})
},
因需要在登录页获取用户名,写在了main.vue中。
链接、领域、客户端均由后端提供。
接口获取keycloak数据中包含登出、更新token接口,可直接调用。
登出:keyclock.logout({redirectUri: 'http://localhost:8080'});url地址是登录首页地址
参考文章:Simply logout from Keycloak – Thomas Suedbroecker's Blog