// KeycloakStore.js import {defineStore} from 'pinia' import Keycloak from 'keycloak-js'…
- User
// KeycloakStore.js import {defineStore} from 'pinia' import Keycloak from 'keycloak-js'
export const useKeycloakStore = defineStore('Keycloak', { state: () => { const keycloak = null return {keycloak} }, // persist: true, persist: myPersistedState, getters: { // keycloak: (state) => state?.keycloak, token: function (state) { return state.keycloak?.token }, username: (state) => state.keycloak?.tokenParsed?.preferred_username, email: (state) => state.keycloak?.tokenParsed?.email }, actions: { //创建定时器 createRefreshTokenTimer(keycloak) { const timer = setInterval(() => { keycloak.updateToken(280).then((refreshed) => { //如果更新了,提醒一下前端,若无就不用处理 // this.keycloak = {...this.keycloak} if (refreshed) { this.keycloak = {... keycloak,token:keycloak.token} console.log("Token 已更新:" + new Date() + '\n' + keycloak.token) } else { console.log("token有效,无需更新") } }).catch(() => { console.error("更新Keycloak Token失败!") }) }, 1000)
code//页面刷新时,清除定时器,避免页面unload时计时器混乱: window.onbeforeunload = () => { clearInterval(timer); } }, //初始化Keycloak对象 initializeKeycloak() { // await this.createRefreshTokenTimer(keycloak); return new Promise((resolve, reject) => { const keycloak = new Keycloak({ url: "http://192.168.1.8:8080/", realm: "sinno", clientId: "sinno_pd_manager", }); keycloak.init({ onLoad: "login-required", checkLoginIframe: false, // otherwise it would reload the window every so seconds enableLogging: true, pkceMethod: 'S256', flow: 'standard', // redirectUri:'/' }).then(async (authenticated) => { if (authenticated) { await keycloak.updateToken(0) this.keycloak = keycloak //把注册的keycloak存到store里 //添加定时器 await this.createRefreshTokenTimer(keycloak); resolve(`首次登录,Keycloak授权成功!\nToken:\n${this.keycloak.token}`) } else { reject.error(new Error(`Keycloak授权失败!${authenticated}`)) window.location.reload() } }) }).then(async (success_msg) => { console.log(success_msg) }).catch((error) => { console.error("首次登录,Keycloak授权失败!", error) window.location.reload() }) }, login() { this.keycloak.login() }, logout() { this.keycloak.logout({ // redirectUri: window.location.href, // redirectUri: window.location.origin, refreshToken: true, idToken: true, accessToken: true }).then(logout => { // Clear cookies after logout document.cookie.split(';').forEach(function (c) { document.cookie = c .replace(/^ +/, '') .replace(/(?:(?:^|.*;\s*) OAID\s*=\s*([^;]*).*$)|^.*$/, ''); }); }); this.keycloak = null } - Assistant
根据代码,
persist选项使用了一个名为myPersistedState的函数来进行状态持久化。然而,在myPersistedState函数中,并没有对keycloak进行任何操作,所以keycloak的值不会被更新。为了解决这个问题,你可以在
myPersistedState函数中将keycloak保存到storage中,然后在创建定时器时重新设置keycloak的值。具体的修改如下所示:javascript - User
一开始登录就可以获取到最新的token如何实现
- Assistant
要在一开始登录时获取到最新的 token,可以在
initializeKeycloak方法中手动更新 token,然后在设置keycloak的值之前进行保存。具体的修改如下所示:
javascriptexport const useKeycloakStore = defineStore('Keycloak', { // ...其他代码... actions: { // ...其他代码... async initializeKeycloak() { // ...其他代码... if (authenticated) { // 更新 token await keycloak.updateToken(0) // 添加定时器 await this.createRefreshTokenTimer(keycloak) // 保存最新的 token keycloak.token = keycloak.token this.keycloak = keycloak // ...其他代码... } }, // ...其他代码... }, })在修改后的
initializeKeycloak方法中,先调用updateToken方法手动更新 token,然后将更新后的 token 保存到keycloak.token中。最后再设置this.keycloak的值,这样就可以获取到最新的 token。