// 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 = {... this.keycloak,toke:this.keycloak.token} console.log("Token 已更新:" + new Date() + '\n' + 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
在代码中,
createRefreshTokenTimer方法里的keycloak.updateToken(280)方法用于更新令牌(token)。更新令牌后,可以通过keycloak.token属性获取最新的令牌值。在更新令牌的回调函数中,将最新的令牌赋值给
this.keycloak。但是在代码中,赋值的属性名写成了toke,应该修改为token。以下是修改后的代码:
createRefreshTokenTimer(keycloak) { const timer = setInterval(() => { keycloak.updateToken(280).then((refreshed) => { if (refreshed) { this.keycloak = { ...this.keycloak, token: this.keycloak.token } console.log("Token 已更新:" + new Date() + '\n' + keycloak.token) } else { console.log("token有效,无需更新") } }).catch(() => { console.error("更新Keycloak Token失败!") }) }, 1000) //页面刷新时,清除定时器,避免页面unload时计时器混乱: window.onbeforeunload = () => { clearInterval(timer); } },修改后的代码将最新的令牌值赋给
token属性,可以通过this.keycloak.token获取最新的令牌。 - 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) { this.keycloak = {... this.keycloak,token:this.keycloak.token} console.log("Token 已更新:" + new Date() + '\n' + 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怎麽解決
- Assistant
在上述代码中,
createRefreshTokenTimer方法用于定期更新令牌(token),并将最新的令牌赋值给this.keycloak.token。然而,该方法传入的参数
keycloak并没有通过this.keycloak进行赋值,导致无法更新到最新的令牌。修复该问题,需要将keycloak赋值给this.keycloak。以下是修改后的代码:
createRefreshTokenTimer(keycloak) { const timer = setInterval(() => { keycloak.updateToken(280).then((refreshed) => { if (refreshed) { this.keycloak = { ...this.keycloak, token: this.keycloak.token // 将最新的令牌赋值给 token }; console.log("Token 已更新:" + new Date() + '\n' + this.keycloak.token); } else { console.log("Token 仍然有效,无需更新"); } }).catch((error) => { console.error("更新 Keycloak Token 失败!", error); }); }, 1000); // 页面刷新时,清除定时器,避免页面 unload 时计时器混乱: window.onbeforeunload = () => { clearInterval(timer); }; },修改后的代码会将最新的令牌赋给
token属性,并且更新this.keycloak对象。请注意,令牌刷新的时间间隔是 280 秒,可以根据实际需要进行调整。另外,为了避免页面刷新造成计时器混乱,将清除定时器的逻辑放在
window.onbeforeunload事件处理程序中。同时,确保在调用
createRefreshTokenTimer方法时传入正确的keycloak对象,如在initializeKeycloak方法中调用:await this.createRefreshTokenTimer(keycloak);通过以上修改,应该能够正确地获取到最新的令牌值。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.