From b7318cd86575ee540464beb20050cb8ee67923cb Mon Sep 17 00:00:00 2001 From: "Fergus MacConnell WLRS:EX" Date: Fri, 20 Sep 2024 15:55:45 -0700 Subject: [PATCH] Current keycloak working state. --- app/frontend/jest.config.js | 3 +- app/frontend/package-lock.json | 6 +- app/frontend/package.json | 2 +- app/frontend/src/common/authenticate.js | 158 +++++++++++++++----- app/frontend/src/common/components/Auth.vue | 9 +- app/frontend/src/common/store/auth.js | 1 + app/frontend/vue.config.js | 10 ++ 7 files changed, 146 insertions(+), 43 deletions(-) diff --git a/app/frontend/jest.config.js b/app/frontend/jest.config.js index bf28a52f6..422069dce 100644 --- a/app/frontend/jest.config.js +++ b/app/frontend/jest.config.js @@ -5,7 +5,8 @@ module.exports = { 'js', 'jsx', 'json', - 'vue' + 'vue', + '.mjs' ], transform: { '^.+\\.vue$': 'vue-jest', diff --git a/app/frontend/package-lock.json b/app/frontend/package-lock.json index ea086633e..a8b42b7a7 100644 --- a/app/frontend/package-lock.json +++ b/app/frontend/package-lock.json @@ -10560,9 +10560,9 @@ "integrity": "sha512-hRkd6/XW4HTsA9vjVpY9tuXJYLSlelnkTmVFu4M9/7MIYQtFcHpbugAU7UbOfjOiVSVYl2fqgBuJ32JUmRo5Ew==" }, "keycloak-js": { - "version": "18.0.0", - "resolved": "https://registry.npmjs.org/keycloak-js/-/keycloak-js-18.0.0.tgz", - "integrity": "sha512-kaD6nrzgYX3NhgwQfVEZiAzaZXua3PSBIBWGWf8fgqPgUdiO8uvYaKV1Ebf43IAB5M8kvubW+2J+eBS+UnWsuw==", + "version": "21.1.2", + "resolved": "https://registry.npmjs.org/keycloak-js/-/keycloak-js-21.1.2.tgz", + "integrity": "sha512-+6r1BvmutWGJBtibo7bcFbHWIlA7XoXRCwcA4vopeJh59Nv2Js0ju2u+t8AYth+C6Cg7/BNfO3eCTbsl/dTBHw==", "requires": { "base64-js": "^1.5.1", "js-sha256": "^0.9.0" diff --git a/app/frontend/package.json b/app/frontend/package.json index 904d769d2..0220241eb 100644 --- a/app/frontend/package.json +++ b/app/frontend/package.json @@ -38,7 +38,7 @@ "vue-select": "^3.1.0", "vuejs-noty": "^0.1.3", "vuex": "^3.0.1", - "keycloak-js": "18.0.0" + "keycloak-js": "21.1.2" }, "devDependencies": { "@vue/cli-plugin-babel": "^3.7.0", diff --git a/app/frontend/src/common/authenticate.js b/app/frontend/src/common/authenticate.js index 1ab2cba1b..4e2b980e1 100644 --- a/app/frontend/src/common/authenticate.js +++ b/app/frontend/src/common/authenticate.js @@ -20,37 +20,77 @@ export default { */ return new Promise((resolve, reject) => { if (!Vue.prototype.$keycloak) { + + // try { + // Vue.prototype.$keycloak = new Keycloak() + + // return Vue.prototype.$keycloak; + + // } catch (error) { + // console.error("Keycloak Instance ERROR: ", error); + // } // Keycloak has not yet been loaded, get Keycloak configuration from the server. ApiService.query('keycloak', {}) .then(response => { + + console.log("Keycloak Config Data: ", response.data) + + const { + url, + 'ssl-required': sslRequired , + resource, + realm, + 'public-client': publicClient, + 'confidential-port': confidentialPort, + clientId, + 'auth-server-url': authServerUrl + } = response.data; /* "A best practice is to load the JavaScript adapter directly from Keycloak Server as it will automatically be updated when you upgrade the server. If you copy the adapter to your web application instead, make sure you upgrade the adapter only after you have upgraded the server."; source : https://www.keycloak.org/docs/latest/securing_apps/index.html#_javascript_adapter: */ - const jsUrl = `${response.data['auth-server-url']}/js/keycloak.js` + // const jsUrl = `${response.data['auth-server-url']}/js/keycloak.js` + // const jsUrl = "https://unpkg.com/keycloak-js@24.0.0/dist/keycloak.min.js" + // Inject the Keycloak javascript into the DOM. - const keyCloakScript = document.createElement('script') - keyCloakScript.onload = () => { - // Construct the Keycloak object and resolve the promise. - Vue.prototype.$keycloak = new Keycloak(response.data) - resolve(Vue.prototype.$keycloak) - } - keyCloakScript.onerror = (e) => { - // This is pretty bad - keycloak didn't load - this should never ever happen. - // There's not much we can do, so we set keycloak to a random empty object and resolve. - console.error(e) - Vue.prototype.$keycloak = {} - resolve(Vue.prototype.$keycloak) - } - keyCloakScript.async = true - keyCloakScript.setAttribute('src', jsUrl) - document.head.appendChild(keyCloakScript) + // const keyCloakScript = document.createElement('script') + + // keyCloakScript.onload = () => { + // // Construct the Keycloak object and resolve the promise. + // Vue.prototype.$keycloak = new Keycloak(response.data) + // resolve(Vue.prototype.$keycloak) + // } + Vue.prototype.$keycloak = new Keycloak({ + url: authServerUrl, + realm, + clientId, + sslRequired, + resource, + publicClient, + confidentialPort, + }) + + resolve(Vue.prototype.$keycloak) + + // keyCloakScript.onerror = (e) => { + // // This is pretty bad - keycloak didn't load - this should never ever happen. + // // There's not much we can do, so we set keycloak to a random empty object and resolve. + // console.error(e) + // Vue.prototype.$keycloak = {} + // resolve(Vue.prototype.$keycloak) + // } + + // keyCloakScript.async = true + // keyCloakScript.setAttribute('src', jsUrl) + // document.head.appendChild(keyCloakScript) }) .catch(error => { + console.error(error) Vue.prototype.$keycloak = {} - reject(error) + resolve(Vue.prototype.$keycloak) + // reject(error) }) } else { // Keycloak has already been loaded, so just resolve the object. @@ -112,26 +152,36 @@ export default { */ return new Promise((resolve, reject) => { this.getInstance() - .then((instance) => { + .then(async (instance) => { + console.log("INSTANCE: ", instance.authenticated) if (instance.authenticated && ApiService.hasAuthHeader() && !instance.isTokenExpired(0)) { // We've already authenticated, have a header, and we've not expired. resolve(instance) } else { - // Attempt to retrieve a stored token, this may avoid us having to refresh the page. - const token = localStorage.getItem('token') - const refreshToken = localStorage.getItem('refreshToken') - const idToken = localStorage.getItem('idToken') - instance.init({ - pkceMethod: 'S256', - onLoad: 'check-sso', - checkLoginIframe: true, - timeSkew: 10, // Allow for some deviation - token, - refreshToken, - idToken, - } - ).then((result) => { + + // this.removeLocalToken() + // instance.clearToken() + // // We update the store reference only after wiring up the API. (Someone might be waiting + // // for login to complete before taking some action. ) + // store.commit('SET_KEYCLOAK', instance) + // resolve(instance) + + try { + console.log("before auth") + const authed = await instance.init({ + pkceMethod: 'S256', + onLoad: 'check-sso', + timeSkew: 10, + checkLoginIframe: false, + token, + refreshToken, + idToken, + }) + + console.log(`User is ${authed ? 'authenticated' : 'not authenticated'}`); + if (instance.authenticated) { + console.log("authenticated") // We may have been authenticated, but the token could be expired. instance.updateToken(60).then(() => { // Store the token to avoid future round trips, and wire up the API @@ -157,9 +207,45 @@ export default { store.commit('SET_KEYCLOAK', instance) resolve(instance) } - }).then((e) => { - reject(e) - }) + + } catch (error) { + console.error('Failed to initialize adapter:', error); + } + // Attempt to retrieve a stored token, this may avoid us having to refresh the page. + const token = localStorage.getItem('token') + const refreshToken = localStorage.getItem('refreshToken') + const idToken = localStorage.getItem('idToken') + + // ).then((result) => { + // if (instance.authenticated) { + // // We may have been authenticated, but the token could be expired. + // instance.updateToken(60).then(() => { + // // Store the token to avoid future round trips, and wire up the API + // this.setLocalToken(instance) + // // We update the store reference only after wiring up the API. (Someone might be waiting + // // for login to complete before taking some action. ) + // // Assumes that store passed in includes a 'SET_KEYCLOAK' mutation! + // store.commit('SET_KEYCLOAK', instance) + // this.scheduleRenewal(instance) + // resolve(instance) + // }).error(() => { + // // The refresh token is expired or was rejected + // this.removeLocalToken() + // instance.clearToken() + // // We update the store reference only after wiring up the API. (Someone might be waiting + // // for login to complete before taking some action. ) + // store.commit('SET_KEYCLOAK', instance) + // resolve(instance) + // }) + // } else { + // // We may have failed to authenticate, for many reasons, e.g. - it may be we never logged in, + // // or have an expired token. + // store.commit('SET_KEYCLOAK', instance) + // resolve(instance) + // } + // }).then((e) => { + // reject(e) + // }) } }) .catch((error) => { diff --git a/app/frontend/src/common/components/Auth.vue b/app/frontend/src/common/components/Auth.vue index 27bd9e809..507b7ddb9 100644 --- a/app/frontend/src/common/components/Auth.vue +++ b/app/frontend/src/common/components/Auth.vue @@ -37,9 +37,13 @@ export default { this.keyCloakLogin() } }, - async keyCloakLogin () { - this.keycloak.init().then(() => { + keyCloakLogin () { + this.keycloak.init({ + checkLoginIframe: false + }).then(() => { + console.log(".then after button click") this.keycloak.login({ idpHint: this.config.sso_idp_hint }).then((authenticated) => { + console.log("after login") if (authenticated) { ApiService.authHeader('JWT', this.keycloak.token) if (window.localStorage) { @@ -49,6 +53,7 @@ export default { } } }).catch((e) => { + console.error("keyCloakLogin: ", e) this.$store.commit(SET_ERROR, { error: 'Cannot contact SSO provider' }) }) }) diff --git a/app/frontend/src/common/store/auth.js b/app/frontend/src/common/store/auth.js index 0036055e4..78279cf7b 100644 --- a/app/frontend/src/common/store/auth.js +++ b/app/frontend/src/common/store/auth.js @@ -11,6 +11,7 @@ const auth = { }, getters: { keycloak (state) { + console.log("state keycloak", state.keycloak) return state.keycloak }, userRoles (state) { diff --git a/app/frontend/vue.config.js b/app/frontend/vue.config.js index a1c3b91cd..a47a1122a 100644 --- a/app/frontend/vue.config.js +++ b/app/frontend/vue.config.js @@ -8,11 +8,21 @@ module.exports = { publicPath: process.env.NODE_ENV === 'production' ? '/gwells/' : '/', configureWebpack: { resolve: { + extensions: ['.mjs', '.js', '.vue', '.json'], alias: { moment: 'moment/src/moment', lodash: 'lodash-es' } }, + module: { + rules: [ + { + test: /\.mjs$/, // Target .mjs files + include: /node_modules/, // Include node_modules (where Keycloak might reside) + type: 'javascript/auto' // Treat .mjs as a JavaScript module + } + ] + }, devServer: { watchOptions: { ignored: /node_modules/,