import {defineStore} from 'pinia' import Keycloak from 'keycloak-js' export const…
- User
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(70).then((refreshed) => { //如果更新了,提醒一下前端,若无就不用处理 // this.keycloak = {...this.keycloak} if (refreshed) { console.log("Token 已更新:" + new Date() + '\n' + keycloak.token), token = keycloak.token
} else { console.log("token有效,无需更新") } }).catch(() => { console.error("更新Keycloak Token失败!") }) }, 1000)//页面刷新时,清除定时器,避免页面unload时计时器混乱: window.onbeforeunload = () => { clearInterval(timer); } }, //初始化Keycloak对象 initializeKeycloak() { 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) { 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 }},
})
function myPersistedState(store) { // 保存到 sessionStorage const storage = sessionStorage } 为什么这段代码我更新了token但原来的token却没有改变
- Assistant
在您的代码中,更新令牌后没有将新令牌分配回state,这是导致原始令牌没有更改的原因。
您可以在
createRefreshTokenTimer方法中更新keycloak.token并将其分配回state.keycloak.token属性。修改createRefreshTokenTimer方法如下:createRefreshTokenTimer(keycloak) { const timer = setInterval(() => { keycloak.updateToken(70).then((refreshed) => { if (refreshed) { console.log("Token 已更新:" + new Date() + '\n' + keycloak.token) this.keycloak = { ...this.keycloak, token: keycloak.token } } else { console.log("token有效,无需更新") } }).catch(() => { console.error("更新Keycloak Token失败!") }) }, 1000) //页面刷新时,清除定时器,避免页面unload时计时器混乱: window.onbeforeunload = () => { clearInterval(timer); } },现在,每次更新令牌时,都会在您的store的
keycloak.token属性中保存新的令牌值。 - User
this.keycloak = { …this.keycloak, token: keycloak.token }这段话报错了
- Assistant
对不起,我在之前的回答中给出了一个错误的解决方案。实际上,您无法直接更改通过
createRefreshTokenTimer方法访问到的this.keycloak属性。当使用defineStore方法定义存储时,返回的是一个Proxy对象,该对象用于处理状态更新和触发相关的依赖。因此,您无法直接通过分配新值来更改状态。为了解决这个问题,您可以创建一个
computed属性来动态获取令牌值,并且在更新令牌时重新计算其值。以下是如何修改代码:import { defineStore } from 'pinia' import Keycloak from 'keycloak-js' export const useKeycloakStore = defineStore('Keycloak', { state: () => ({ keycloak: null }), // persist: true, persist: myPersistedState, getters: { keycloak: (state) => state.keycloak, token: function () { return this.keycloak?.token }, username: () => this.keycloak?.tokenParsed?.preferred_username, email: () => this.keycloak?.tokenParsed?.email }, actions: { // 创建定时器 createRefreshTokenTimer(keycloak) { const timer = setInterval(() => { keycloak.updateToken(70).then((refreshed) => { if (refreshed) { console.log("Token 已更新:" + new Date() + '\n' + keycloak.token) this.$patch({ keycloak: { token: keycloak.token } }) } else { console.log("token有效,无需更新") } }).catch(() => { console.error("更新Keycloak Token失败!") }) }, 1000) // 页面刷新时,清除定时器,避免页面unload时计时器混乱 window.onbeforeunload = () => { clearInterval(timer); } }, // 初始化Keycloak对象 initializeKeycloak() { 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, enableLogging: true, pkceMethod: 'S256', flow: 'standard', // redirectUri:'/' }).then(async (authenticated) => { if (authenticated) { this.keycloak = keycloak await this.createRefreshTokenTimer(keycloak); resolve(`首次登录,Keycloak授权成功!\nToken:\n${this.keycloak.token}`) } else { reject(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({ 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 } }, }) function myPersistedState(store) { const storage = sessionStorage }现在,每当您更新令牌时,
tokengetter 将返回新的令牌值。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.