├── .editorconfig ├── .github └── workflows │ └── inactive_issues.yml ├── .gitignore ├── .prettierignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── eslint.config.js ├── jest.config.js ├── package-lock.json ├── package.json ├── prettier.config.js ├── release.config.js ├── rollup.config.js ├── src ├── composable.test.ts ├── composable.ts ├── const.test.ts ├── const.ts ├── index.ts ├── keycloak.test.ts ├── keycloak.ts ├── plugin.test.ts ├── plugin.ts ├── state.test.ts ├── state.ts ├── utils.test.ts └── utils.ts └── tsconfig.json /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | charset = utf-8 7 | indent_style = space 8 | indent_size = 2 9 | end_of_line = lf 10 | insert_final_newline = true 11 | trim_trailing_whitespace = true 12 | 13 | [*.md] 14 | trim_trailing_whitespace = false 15 | -------------------------------------------------------------------------------- /.github/workflows/inactive_issues.yml: -------------------------------------------------------------------------------- 1 | name: Close inactive issues 2 | on: 3 | schedule: 4 | - cron: '30 6 * * *' 5 | 6 | permissions: 7 | issues: write 8 | pull-requests: write 9 | 10 | jobs: 11 | close-issues: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/stale@v9 15 | with: 16 | days-before-issue-stale: 21 17 | days-before-issue-close: 7 18 | stale-issue-label: 'stale' 19 | stale-issue-message: > 20 | This issue was marked as stale because it had no recent activity. 21 | It will be closed soon if no further activity occurs. 22 | close-issue-message: 'This issue was closed because it had no recent activity.' 23 | days-before-pr-stale: -1 24 | days-before-pr-close: -1 25 | repo-token: ${{ secrets.GITHUB_TOKEN }} 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | .npmrc 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Microbundle cache 58 | .rpt2_cache/ 59 | .rts2_cache_cjs/ 60 | .rts2_cache_es/ 61 | .rts2_cache_umd/ 62 | 63 | # Optional REPL history 64 | .node_repl_history 65 | 66 | # Output of 'npm pack' 67 | *.tgz 68 | 69 | # Yarn Integrity file 70 | .yarn-integrity 71 | 72 | # dotenv environment variables file 73 | .env 74 | .env.test 75 | 76 | # parcel-bundler cache (https://parceljs.org/) 77 | .cache 78 | 79 | # Next.js build output 80 | .next 81 | 82 | # Nuxt.js build / generate output 83 | .nuxt 84 | dist 85 | dist-transpiled 86 | 87 | 88 | # Gatsby files 89 | .cache/ 90 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 91 | # https://nextjs.org/blog/next-9-1#public-directory-support 92 | # public 93 | 94 | # vuepress build output 95 | .vuepress/dist 96 | 97 | # Serverless directories 98 | .serverless/ 99 | 100 | # FuseBox cache 101 | .fusebox/ 102 | 103 | # DynamoDB Local files 104 | .dynamodb/ 105 | 106 | # TernJS port file 107 | .tern-port 108 | .idea 109 | /ui-library.iml 110 | /temp 111 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | .github/ 2 | *.md 3 | package-lock.json 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [3.3.2](https://github.com/JoseGoncalves/vue-keycloak/compare/v3.3.1...v3.3.2) (2025-10-15) 2 | 3 | ### Bug Fixes 4 | 5 | * change the return type of createKeycloak() to indicate that it may fail ([7d88d23](https://github.com/JoseGoncalves/vue-keycloak/commit/7d88d23eb9f5540a0d32de5b9ee143926c0b9837)) 6 | * support keycloak-js v26.2.1 ([1282b8b](https://github.com/JoseGoncalves/vue-keycloak/commit/1282b8ba8e580ab5e673af46b381e3f7aa1b0739)) 7 | 8 | ## [3.3.1](https://github.com/JoseGoncalves/vue-keycloak/compare/v3.3.0...v3.3.1) (2025-06-17) 9 | 10 | ### Bug Fixes 11 | 12 | * reject getToken() promise on undefined token ([0afeec8](https://github.com/JoseGoncalves/vue-keycloak/commit/0afeec8aa07729b19c8e1d35183337909462c412)) 13 | 14 | ### Internal 15 | 16 | * use globalIgnores() in ESLint config ([64856ee](https://github.com/JoseGoncalves/vue-keycloak/commit/64856ee044efbe2e107666e08c08167711f4c583)) 17 | * use stricter typescript-eslint rules ([3697e65](https://github.com/JoseGoncalves/vue-keycloak/commit/3697e65fe9eea3d51c3f22ee7d89c1543e3f1646)) 18 | 19 | ## [3.3.0](https://github.com/JoseGoncalves/vue-keycloak/compare/v3.2.1...v3.3.0) (2025-04-30) 20 | 21 | ### Features 22 | 23 | * provide a meaningful error message even if keycloak-js does not throw one ([fd237f9](https://github.com/JoseGoncalves/vue-keycloak/commit/fd237f9e22722243306128c2ef796414fe1cd991)) 24 | 25 | ## [3.2.1](https://github.com/JoseGoncalves/vue-keycloak/compare/v3.2.0...v3.2.1) (2025-04-15) 26 | 27 | ### Bug Fixes 28 | 29 | * Revert "use ShallowRef for non-primitive types" ([5d4ef42](https://github.com/JoseGoncalves/vue-keycloak/commit/5d4ef42a887615ca563cba2c6f1654a56165432b)) 30 | 31 | ## [3.2.0](https://github.com/JoseGoncalves/vue-keycloak/compare/v3.1.1...v3.2.0) (2025-04-15) 32 | 33 | ### Features 34 | 35 | * improved error handling and return error info in composable ([ef5fb01](https://github.com/JoseGoncalves/vue-keycloak/commit/ef5fb01e16672853e7655dd4770a81e0cb38a844)) 36 | 37 | ### Internal 38 | 39 | * remove redundant check in isFunction() ([a988899](https://github.com/JoseGoncalves/vue-keycloak/commit/a9888998522f02e044bb399a6a18ff43702ae2d3)) 40 | * use ShallowRef for non-primitive types ([9b76cb0](https://github.com/JoseGoncalves/vue-keycloak/commit/9b76cb07a2a1daa3200c86d6bc0db3f4b653f923)) 41 | 42 | ## [3.1.1](https://github.com/JoseGoncalves/vue-keycloak/compare/v3.1.0...v3.1.1) (2025-03-16) 43 | 44 | ### Bug Fixes 45 | 46 | * better roles type checking in hasRoles() & hasResourceRoles() ([80d4ca6](https://github.com/JoseGoncalves/vue-keycloak/commit/80d4ca6e8488ebed7b2949b41280b0e93a883d84)) 47 | 48 | ## [3.1.0](https://github.com/JoseGoncalves/vue-keycloak/compare/v3.0.1...v3.1.0) (2024-10-06) 49 | 50 | 51 | ### Features 52 | 53 | * add support to Keycloak 26 ([fd7c7a7](https://github.com/JoseGoncalves/vue-keycloak/commit/fd7c7a7bde0b65b25ee105c254cc281986e9233b)) 54 | 55 | ## [3.0.1](https://github.com/JoseGoncalves/vue-keycloak/compare/v3.0.0...v3.0.1) (2024-09-13) 56 | 57 | 58 | ### Bug Fixes 59 | 60 | * corrected config param type in createKeycloak ([11c311f](https://github.com/JoseGoncalves/vue-keycloak/commit/11c311f1d127e1916d79c15b20e032ee11c7b529)) 61 | 62 | ## [3.0.0](https://github.com/JoseGoncalves/vue-keycloak/compare/v2.7.1...v3.0.0) (2024-06-17) 63 | 64 | 65 | ### Breaking Changes 66 | 67 | * keycloak is now a reactive reference to the keycloak-js adapter instance ([a199c5d](https://github.com/JoseGoncalves/vue-keycloak/commit/a199c5d7b5fdcf9ecbfa4b996d67b0b673d475e5)) 68 | * minimum Vue version is 3.4.0 ([d7e9a18](https://github.com/JoseGoncalves/vue-keycloak/commit/d7e9a18ff36d37e5a61ae0327d7297ecfb6a2762)) 69 | 70 | 71 | ### Bug Fixes 72 | 73 | * fixed VueKeycloakPluginConfig type ([9e4b6ba](https://github.com/JoseGoncalves/vue-keycloak/commit/9e4b6bad1d3f35f94102400fda15233a1ffb1380)) 74 | 75 | 76 | ### Internal 77 | 78 | * remove unnecessary isPromise check on plugin install ([086f8e3](https://github.com/JoseGoncalves/vue-keycloak/commit/086f8e3766afa7b1fe460fcfebb7013d00a854e0)) 79 | 80 | ## [2.7.1](https://github.com/JoseGoncalves/vue-keycloak/compare/v2.7.0...v2.7.1) (2024-06-13) 81 | 82 | 83 | ### Bug Fixes 84 | 85 | * expose plugin install method for typescript ([5ad9d99](https://github.com/JoseGoncalves/vue-keycloak/commit/5ad9d999ebcc241ad6b2ec5ae09bd486cac0ef4e)) 86 | 87 | ## [2.7.0](https://github.com/JoseGoncalves/vue-keycloak/compare/v2.6.0...v2.7.0) (2024-06-11) 88 | 89 | 90 | ### Features 91 | 92 | * add support to Keycloak 25 ([0300a86](https://github.com/JoseGoncalves/vue-keycloak/commit/0300a86f1c530d7fff63debb81b9f4d05a5070f0)) 93 | 94 | ## [2.6.0](https://github.com/JoseGoncalves/vue-keycloak/compare/v2.5.0...v2.6.0) (2024-03-04) 95 | 96 | 97 | ### Features 98 | 99 | * add support to Keycloak 24 ([27427bb](https://github.com/JoseGoncalves/vue-keycloak/commit/27427bb39c84a4b5b04211b31c8e65b046ff0b7e)) 100 | 101 | ## [2.5.0](https://github.com/JoseGoncalves/vue-keycloak/compare/v2.4.0...v2.5.0) (2024-02-14) 102 | 103 | 104 | ### Features 105 | 106 | * broader keycloak-js peer dependency (compatible with versions 18 to 23) ([ee32817](https://github.com/JoseGoncalves/vue-keycloak/commit/ee328177b17d5e242dd8bdd6604577a4a7ff5422)) 107 | * drop support to load config with an HTTP request ([1c56a68](https://github.com/JoseGoncalves/vue-keycloak/commit/1c56a689a6fb5624bf2bc66d6e9e5daaeb497692)) 108 | 109 | 110 | ### Bug Fixes 111 | 112 | * fix Intellisense not resolving module ([094bad2](https://github.com/JoseGoncalves/vue-keycloak/commit/094bad20663e654718f9471bc1b865580437b55a)) 113 | 114 | 115 | ### Internal 116 | 117 | * reformat eslint config ([65f9a51](https://github.com/JoseGoncalves/vue-keycloak/commit/65f9a517fa2574bd749558ace12a5663754d9370)) 118 | * replace deprecated KeycloakInstance with Keycloak ([80eeafd](https://github.com/JoseGoncalves/vue-keycloak/commit/80eeafd19a95862317f0983785e9ba427ba149d3)) 119 | * replace getKeycloak call with $keycloak in createKeycloak ([83773c2](https://github.com/JoseGoncalves/vue-keycloak/commit/83773c24b62f4f272f0fc144ea604153034becfa)) 120 | 121 | ## [2.4.0](https://github.com/JoseGoncalves/vue-keycloak/compare/v2.3.3...v2.4.0) (2024-02-06) 122 | 123 | 124 | ### Features 125 | 126 | * added 'userId' field to the reactive state ([732524d](https://github.com/JoseGoncalves/vue-keycloak/commit/732524dc0983d44b72064ca6527f2b4a22e5e67f)) 127 | * changed build target to es2019 ([95d9c3e](https://github.com/JoseGoncalves/vue-keycloak/commit/95d9c3e9af392daa81fb1d79b87f2a73ef90738d)) 128 | 129 | 130 | ### Bug Fixes 131 | 132 | * fixed composable typings ([bdfdeaf](https://github.com/JoseGoncalves/vue-keycloak/commit/bdfdeafeb892aa4165f182af2048394b93f63127)) 133 | 134 | ### [2.3.3](https://github.com/JoseGoncalves/vue-keycloak/compare/v2.3.2...v2.3.3) (2024-01-30) 135 | 136 | 137 | ### Bug Fixes 138 | 139 | * set typings inside package.json "exports" to allow proper building in typescript projects ([c5691d0](https://github.com/JoseGoncalves/vue-keycloak/commit/c5691d0f24968a39ebd3bb16c45af2529af9e8c9)) 140 | 141 | ### [2.3.2](https://github.com/JoseGoncalves/vue-keycloak/compare/v2.3.1...v2.3.2) (2024-01-27) 142 | 143 | 144 | ### Bug Fixes 145 | 146 | * some tools still don't parse package.exports, so reintroduce package.main for full compatibility. ([4a5dbb2](https://github.com/JoseGoncalves/vue-keycloak/commit/4a5dbb233c32314be5867e6022fc7320578d9465)) 147 | 148 | ### [2.3.1](https://github.com/JoseGoncalves/vue-keycloak/compare/v2.3.0...v2.3.1) (2024-01-27) 149 | 150 | 151 | ### Bug Fixes 152 | 153 | * use conditional exports in package.json to support vitest ([2c995c7](https://github.com/JoseGoncalves/vue-keycloak/commit/2c995c7a003fc0b17f6fe2f33d0536635ab21cab)) 154 | 155 | ## [2.3.0](https://github.com/JoseGoncalves/vue-keycloak/compare/v2.2.0...v2.3.0) (2024-01-14) 156 | 157 | 158 | ### Features 159 | 160 | * use tokenParsed instead of jwt-decode ([4a7e5be](https://github.com/JoseGoncalves/vue-keycloak/commit/4a7e5be6e4182ee9293cb0f7689ccae5a436d33d)) 161 | 162 | ## [2.2.0](https://github.com/JoseGoncalves/vue-keycloak/compare/v2.1.0...v2.2.0) (2023-11-23) 163 | 164 | 165 | ### Features 166 | 167 | * upgrade jwt-decode ([4318123](https://github.com/JoseGoncalves/vue-keycloak/commit/43181238bf4defa871a6773164d8c6d113bde35d)) 168 | * upgrade keycloak-js to 23.0.0 ([863cf73](https://github.com/JoseGoncalves/vue-keycloak/commit/863cf739f00cd007ba414ab049e4c775e3ecb5b5)) 169 | 170 | ## [2.1.0](https://github.com/JoseGoncalves/vue-keycloak/compare/v2.0.1...v2.1.0) (2023-11-21) 171 | 172 | 173 | ### Features 174 | 175 | * add optional minValidity parameter to getToken() ([7f7dbbb](https://github.com/JoseGoncalves/vue-keycloak/commit/7f7dbbb86b30ae3b3b47bef70089839840ac6b26)) 176 | 177 | ### [2.0.1](https://github.com/JoseGoncalves/vue-keycloak/compare/v2.0.0...v2.0.1) (2023-11-02) 178 | 179 | 180 | ### Bug Fixes 181 | 182 | * validate realm_access claim existence in token ([2f6a1ba](https://github.com/JoseGoncalves/vue-keycloak/commit/2f6a1ba75ddbcca1f7319aae46a9980b52fe274b)) 183 | 184 | # [2.0.0](https://github.com/JoseGoncalves/vue-keycloak/compare/v1.11.1...v2.0.0) (2023-10-04) 185 | 186 | 187 | ### Breaking Changes 188 | 189 | * no need to export getKeycloak() as the keycloak instance is exposed in useKeycloak() ([0f04e4c](https://github.com/JoseGoncalves/vue-keycloak/commit/0f04e4c9292ae5c3d70cb5517e4452cd05354cac)) 190 | 191 | ### Features 192 | 193 | * broader keycloak-js peer dependency (compatible with 20.x, 21.x & 22.x) ([fcfef2c](https://github.com/JoseGoncalves/vue-keycloak/commit/fcfef2cbe4afeae0352f40fbf43f2f8435348e80)) 194 | * upgrade keycloak-js to 22.0.4 ([99ed3e6](https://github.com/JoseGoncalves/vue-keycloak/commit/99ed3e692e7d26e0a977c433ae796c9ab8645b66)) 195 | 196 | ## [1.11.1](https://github.com/JoseGoncalves/vue-keycloak/compare/v1.11.0...v1.11.1) (2023-09-28) 197 | 198 | 199 | ### Bug Fixes 200 | 201 | * add compatibility with keycloak-js v20 ([7c1d52d](https://github.com/JoseGoncalves/vue-keycloak/commit/7c1d52d3806de77f7ac2b3d11caa7df4d85486e2)) 202 | 203 | ## [1.11.0](https://github.com/JoseGoncalves/vue-keycloak/compare/v1.10.0...v1.11.0) (2023-09-28) 204 | 205 | 206 | ### Features 207 | 208 | * upgrade keycloak-js to 22.0.3 ([7a913a3](https://github.com/JoseGoncalves/vue-keycloak/commit/7a913a34e382a1c7049c5917fa27ec41bd9a050b)) 209 | 210 | ## [1.10.0](https://github.com/JoseGoncalves/vue-keycloak/compare/v1.9.1...v1.10.0) (2023-07-17) 211 | 212 | 213 | ### Features 214 | 215 | * upgrade keycloak-js to 21.1.2 ([bd28b6d](https://github.com/JoseGoncalves/vue-keycloak/commit/bd28b6d99e5b22795f1ba1f104341d12ae4bb0b8)) 216 | 217 | ### [1.9.1](https://github.com/JoseGoncalves/vue-keycloak/compare/v1.9.0...v1.9.1) (2023-05-04) 218 | 219 | 220 | ### Bug Fixes 221 | 222 | * Fix release ([55f2322](https://github.com/JoseGoncalves/vue-keycloak/commit/55f23226f9764bb3631fee2e222fdf8148f8cdb6)) 223 | 224 | ## [1.9.0](https://github.com/JoseGoncalves/vue-keycloak/compare/v1.8.4...v1.9.0) (2023-05-04) 225 | 226 | 227 | ### Features 228 | 229 | * Stop using deprecated functionalities of Keycloak JS ([6577272](https://github.com/JoseGoncalves/vue-keycloak/commit/657727249bb8abd53cb59323206e8e4053286187)) 230 | * upgrade keycloak-js to 21.1.1 ([023b0bd](https://github.com/JoseGoncalves/vue-keycloak/commit/023b0bd8305d30f1aff372ce5395b90dc94cf0e2)) 231 | 232 | 233 | ### Bug Fixes 234 | 235 | * downgraded semantic-release to support legacy authentication using NPM_USERNAME and NPM_PASSWORD ([4755ca4](https://github.com/JoseGoncalves/vue-keycloak/commit/4755ca4b367d39adc6bb2dd9235f63ce7b0cce22)) 236 | 237 | ### [1.8.4](https://github.com/JoseGoncalves/vue-keycloak/compare/v1.8.3...v1.8.4) (2023-01-08) 238 | 239 | ### [1.8.3](https://github.com/JoseGoncalves/vue-keycloak/compare/v1.8.2...v1.8.3) (2023-01-06) 240 | 241 | 242 | ### Bug Fixes 243 | 244 | * removal of callback setting ([652a60e](https://github.com/JoseGoncalves/vue-keycloak/commit/652a60e4b631c69903e3b2e49864dfdf1f9e9bab)) 245 | 246 | ### [1.8.2](https://github.com/JoseGoncalves/vue-keycloak/compare/v1.8.1...v1.8.2) (2023-01-05) 247 | 248 | 249 | ### Bug Fixes 250 | 251 | * added check for required config ([93d0a75](https://github.com/JoseGoncalves/vue-keycloak/commit/93d0a7566d26c97477f061098365178c8cd50ceb)) 252 | 253 | ### [1.8.1](https://github.com/JoseGoncalves/vue-keycloak/compare/v1.8.0...v1.8.1) (2023-01-05) 254 | 255 | 256 | ### Bug Fixes 257 | 258 | * update README and build environment ([877dc45](https://github.com/JoseGoncalves/vue-keycloak/commit/877dc451752f46ceae8eb1780acb4454bf5a254f)) 259 | 260 | ## [1.8.0](https://github.com/JoseGoncalves/vue-keycloak/compare/v1.7.1...v1.8.0) (2023-01-03) 261 | 262 | 263 | ### Features 264 | 265 | * Updated to keycloak-js 20.0.2. ([e696c35](https://github.com/JoseGoncalves/vue-keycloak/commit/e696c355d58d0dea1259c1155fdff7af8dc6ae6d)) 266 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2021 Baloise Group 191 | Copyright 2021-present INOV - Instituto de Engenharia de Sistemas e Computadores Inovação 192 | 193 | Licensed under the Apache License, Version 2.0 (the "License"); 194 | you may not use this file except in compliance with the License. 195 | You may obtain a copy of the License at 196 | 197 | http://www.apache.org/licenses/LICENSE-2.0 198 | 199 | Unless required by applicable law or agreed to in writing, software 200 | distributed under the License is distributed on an "AS IS" BASIS, 201 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 202 | See the License for the specific language governing permissions and 203 | limitations under the License. 204 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 9 | 12 | 13 |
4 | 5 | 7 | ➕ 8 | 10 | 11 |
14 | 15 | # vue-keycloak 16 | [![NPM Version](https://img.shields.io/npm/v/%40josempgon%2Fvue-keycloak)](https://www.npmjs.com/package/@josempgon/vue-keycloak) 17 | [![npm bundle size](https://img.shields.io/bundlephobia/min/%40josempgon%2Fvue-keycloak)](https://bundlephobia.com/package/@josempgon/vue-keycloak) 18 | [![NPM Downloads](https://img.shields.io/npm/dm/%40josempgon%2Fvue-keycloak)](https://npm-stat.com/charts.html?package=%40josempgon%2Fvue-keycloak) 19 | 20 | A small Vue wrapper library for the [Keycloak JavaScript adapter](https://www.keycloak.org/securing-apps/javascript-adapter). 21 | 22 | > This library is made for [Vue 3](https://vuejs.org/) with the [Composition API](https://vuejs.org/guide/extras/composition-api-faq.html#what-is-composition-api). 23 | 24 | ## Installation 25 | 26 | Using npm: 27 | 28 | ```bash 29 | npm install @josempgon/vue-keycloak 30 | ``` 31 | 32 | Using yarn: 33 | 34 | ```bash 35 | yarn add @josempgon/vue-keycloak keycloak-js 36 | ``` 37 | 38 | Using pnpm: 39 | 40 | ```bash 41 | pnpm add @josempgon/vue-keycloak keycloak-js 42 | ``` 43 | 44 | ## Use Plugin 45 | 46 | Import the library into your Vue app entry point. 47 | 48 | ```typescript 49 | import { vueKeycloak } from '@josempgon/vue-keycloak' 50 | ``` 51 | 52 | Apply the library to the Vue app instance. 53 | 54 | ```typescript 55 | const app = createApp(App) 56 | 57 | app.use(vueKeycloak, { 58 | config: { 59 | url: 'http://keycloak-server', 60 | realm: 'my-realm', 61 | clientId: 'my-app', 62 | } 63 | }) 64 | ``` 65 | 66 | ### Configuration 67 | 68 | | Object | Type | Required | Description | 69 | | ----------- | --------------------------------------------- | -------- | ---------------------------------------- | 70 | | config | [`KeycloakConfig`][Config] | Yes | Keycloak configuration. | 71 | | initOptions | [`KeycloakInitOptions`][InitOptions] | No | Keycloak init options. | 72 | 73 | #### `initOptions` Default Value 74 | 75 | ```typescript 76 | { 77 | flow: 'standard', 78 | checkLoginIframe: false, 79 | onLoad: 'login-required', 80 | } 81 | ``` 82 | 83 | #### Dynamic Keycloak Configuration 84 | Use the example below to generate a dynamic Keycloak configuration. In that example the Keycloak adapter is initialized in silent `check-sso` mode. Be aware that this mode could have limited functionality with recent browser versions (check [Modern Browsers with Tracking Protection](https://www.keycloak.org/securing-apps/javascript-adapter#_modern_browsers) for additional info). 85 | 86 | ```typescript 87 | app.use(vueKeycloak, async () => { 88 | const url = await getAuthBaseUrl() 89 | const silentCheckSsoRedirectUri = `${location.origin}/silent-check-sso.html` 90 | return { 91 | config: { 92 | url, 93 | realm: 'my-realm', 94 | clientId: 'my-app', 95 | }, 96 | initOptions: { 97 | onLoad: 'check-sso', 98 | silentCheckSsoRedirectUri, 99 | }, 100 | } 101 | }) 102 | ``` 103 | 104 | ### Use with vue-router 105 | If you need to wait for authentication to complete before proceeding with your Vue app setup, for instance, because you are using the `vue-router` package and need to initialize the router only after the authentication process is completed, you should initialize your app in the following way: 106 | 107 | **router/index.js** 108 | ```typescript 109 | import { createRouter, createWebHistory } from 'vue-router' 110 | 111 | const routes = [ /* Your routes */ ] 112 | 113 | const initRouter = () => { 114 | const history = createWebHistory(import.meta.env.BASE_URL) 115 | return createRouter({ history, routes }) 116 | } 117 | 118 | export { initRouter } 119 | ``` 120 | 121 | **main.js** 122 | ```javascript 123 | import { createApp } from 'vue' 124 | import { vueKeycloak } from '@josempgon/vue-keycloak' 125 | import vueKeycloakConfig from './config/vueKeycloak.js' 126 | import App from './App.vue' 127 | import { initRouter } from './router' 128 | 129 | const app = createApp(App) 130 | 131 | await vueKeycloak.install(app, vueKeycloakConfig) 132 | 133 | app.use(initRouter()) 134 | app.mount('#app') 135 | ``` 136 | 137 | If you are building for a browser that does not support [Top-level await](https://caniuse.com/mdn-javascript_operators_await_top_level), you should wrap the Vue plugin and router initialization in an async [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE): 138 | 139 | ```javascript 140 | (async () => { 141 | await vueKeycloak.install(app, vueKeycloakConfig); 142 | 143 | app.use(initRouter()); 144 | app.mount('#app'); 145 | })(); 146 | ``` 147 | 148 | ## Use Token 149 | 150 | A helper function is exported to manage the access token. 151 | 152 | ### getToken 153 | 154 | | Function | Type | Description | 155 | | ---------------- | ------------------------------------------------------ | ---------------------------------------------------------------------- | 156 | | getToken |
(minValidity?: number) => Promise\
| Returns a promise that resolves with the current access token. | 157 | 158 | The token will be refreshed if expires within `minValidity` seconds. The `minValidity` parameter is optional and defaults to 10. If -1 is passed as `minValidity`, the token will be forcibly refreshed. 159 | 160 | A typical usage for this function is to be called before every API call, using a request interceptor in your HTTP client library. 161 | 162 | ```typescript 163 | import axios from 'axios' 164 | import { getToken } from '@josempgon/vue-keycloak' 165 | 166 | // Create an instance of axios with the base URL read from the environment 167 | const baseURL = import.meta.env.VITE_API_URL 168 | const instance = axios.create({ baseURL }) 169 | 170 | // Request interceptor for API calls 171 | instance.interceptors.request.use( 172 | async config => { 173 | const token = await getToken() 174 | config.headers['Authorization'] = `Bearer ${token}` 175 | return config 176 | }, 177 | error => { 178 | Promise.reject(error) 179 | }, 180 | ) 181 | ``` 182 | 183 | ## Composition API 184 | 185 | ```vue 186 | 194 | ``` 195 | 196 | ### useKeycloak 197 | 198 | The `useKeycloak` function exposes the following data. 199 | 200 | ```typescript 201 | import { useKeycloak } from '@josempgon/vue-keycloak' 202 | 203 | const { 204 | // Reactive State 205 | keycloak, 206 | isAuthenticated, 207 | isPending, 208 | hasFailed, 209 | error, 210 | token, 211 | decodedToken, 212 | username, 213 | userId, 214 | roles, 215 | resourceRoles, 216 | 217 | // Functions 218 | hasRoles, 219 | hasResourceRoles, 220 | } = useKeycloak() 221 | ``` 222 | #### Reactive State 223 | 224 | | State | Type | Description | 225 | | --------------- | ------------------------------------------------------ | ------------------------------------------------------------------- | 226 | | keycloak | `ShallowRef<`[`Keycloak`][Instance]`>` | Instance of the keycloak-js adapter. | 227 | | isAuthenticated | `Ref` | If `true` the user is authenticated. | 228 | | isPending | `Ref` | If `true` the authentication request is still pending. | 229 | | hasFailed | `Ref` | If `true` an error ocurred on initialization or Keycloak request. | 230 | | error | `Ref` | Info on error that ocurred (null if no error) | 231 | | token | `Ref` | Raw value of the access token. | 232 | | decodedToken | `Ref<`[`KeycloakTokenParsed`][TokenParsed]`>` | Decoded value of the access token. | 233 | | username | `Ref` | Username. Extracted from `decodedToken['preferred_username']`. | 234 | | userId | `Ref` | User identifier. Extracted from `decodedToken['sub']`. | 235 | | roles | `Ref` | List of the user's roles. | 236 | | resourceRoles | `Ref` | List of the user's roles in specific resources. | 237 | 238 | #### Functions 239 | 240 | | Function | Type | Description | 241 | | ---------------- | --------------------------------------------------------- | ----------------------------------------------------------------- | 242 | | hasRoles |
(roles: string[]) => boolean
| Returns `true` if the user has all the given roles. | 243 | | hasResourceRoles |
(roles: string[], resource: string) => boolean
| Returns `true` if the user has all the given roles in a resource. | 244 | 245 | # License 246 | 247 | This project is licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). 248 | 249 | Originally developed by Gery Hirschfeld (2021). 250 | 251 | Maintained and extended by José Miguel Gonçalves (2021-present). 252 | 253 | [Config]: https://github.com/keycloak/keycloak-js/blob/26.2.1/lib/keycloak.d.ts#L27-L40 254 | [InitOptions]: https://github.com/keycloak/keycloak-js/blob/26.2.1/lib/keycloak.d.ts#L82-L231 255 | [TokenParsed]: https://github.com/keycloak/keycloak-js/blob/26.2.1/lib/keycloak.d.ts#L360-L375 256 | [Instance]: https://github.com/keycloak/keycloak-js/blob/26.2.1/lib/keycloak.d.ts#L399-L685 257 | -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | import { globalIgnores } from 'eslint/config' 2 | import eslint from '@eslint/js' 3 | import tseslint from 'typescript-eslint' 4 | 5 | export default tseslint.config( 6 | globalIgnores(['**/dist/**', '**/dist-transpiled/**']), 7 | eslint.configs.recommended, 8 | tseslint.configs.strict, 9 | tseslint.configs.stylistic, 10 | { 11 | files: ['**/*.test.ts'], 12 | rules: { 13 | '@typescript-eslint/no-empty-function': 'off', 14 | }, 15 | }, 16 | ) 17 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | testEnvironment: 'jsdom', 3 | roots: ['/src'], 4 | testMatch: ['**/__tests__/**/*.+(ts|tsx|js)', '**/?(*.)+(spec|test).+(ts|tsx|js)'], 5 | transform: { 6 | '^.+\\.(ts|tsx)$': 'ts-jest', 7 | }, 8 | } 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@josempgon/vue-keycloak", 3 | "version": "3.3.2", 4 | "description": "Keycloak plugin for Vue 3 with Composition API", 5 | "author": { 6 | "name": "Gery Hirschfeld", 7 | "email": "gerhard.hirschfeld@baloise.ch", 8 | "url": "https://github.com/hirsch88" 9 | }, 10 | "contributors": [ 11 | "José Miguel Gonçalves " 12 | ], 13 | "homepage": "https://github.com/JoseGoncalves/vue-keycloak", 14 | "repository": { 15 | "type": "git", 16 | "url": "git+ssh://git@github.com/JoseGoncalves/vue-keycloak.git" 17 | }, 18 | "scripts": { 19 | "test": "jest", 20 | "test:watch": "jest --watchAll", 21 | "build": "npm run build:clean && npm run build:compile && npm run build:bundle", 22 | "build:clean": "rimraf dist && rimraf dist-transpiled", 23 | "build:compile": "tsc -p .", 24 | "build:bundle": "rollup --config rollup.config.js", 25 | "clean": "npm run build:clean && rimraf node_modules", 26 | "lint": "eslint .", 27 | "lint:fix": "npm run lint -- --fix", 28 | "format": "prettier --write .", 29 | "format:check": "prettier --check .", 30 | "release": "semantic-release --no-ci" 31 | }, 32 | "type": "module", 33 | "main": "./dist/index.cjs", 34 | "types": "./dist/types/index.d.ts", 35 | "exports": { 36 | "require": "./dist/index.cjs", 37 | "import": "./dist/index.mjs", 38 | "types": "./dist/types/index.d.ts" 39 | }, 40 | "files": [ 41 | "dist/" 42 | ], 43 | "keywords": [ 44 | "vue", 45 | "keycloak", 46 | "keycloak-js", 47 | "composition-api" 48 | ], 49 | "license": "Apache-2.0", 50 | "peerDependencies": { 51 | "keycloak-js": "18 - 26", 52 | "vue": "^3.4.0" 53 | }, 54 | "devDependencies": { 55 | "@eslint/js": "^9.37.0", 56 | "@semantic-release/changelog": "^6.0.3", 57 | "@semantic-release/git": "^10.0.1", 58 | "@types/jest": "^30.0.0", 59 | "conventional-changelog-conventionalcommits": "^9.1.0", 60 | "eslint": "^9.37.0", 61 | "jest": "^30.2.0", 62 | "jest-environment-jsdom": "^30.2.0", 63 | "keycloak-js": "^26.2.1", 64 | "prettier": "^3.6.2", 65 | "rimraf": "^6.0.1", 66 | "rollup": "^4.52.4", 67 | "semantic-release": "^24.2.9", 68 | "ts-jest": "^29.4.5", 69 | "typescript": "~5.9.3", 70 | "typescript-eslint": "^8.46.1", 71 | "vue": "^3.5.22" 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /prettier.config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | arrowParens: 'avoid', 3 | printWidth: 120, 4 | quoteProps: 'consistent', 5 | semi: false, 6 | singleQuote: true, 7 | } 8 | -------------------------------------------------------------------------------- /release.config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | plugins: [ 3 | [ 4 | '@semantic-release/commit-analyzer', 5 | { 6 | releaseRules: [ 7 | { type: 'breaking', release: 'major' }, 8 | { type: 'refactor', release: 'patch' }, 9 | ], 10 | }, 11 | ], 12 | [ 13 | '@semantic-release/release-notes-generator', 14 | { 15 | preset: 'conventionalCommits', 16 | presetConfig: { 17 | types: [ 18 | { 19 | type: 'breaking', 20 | section: 'Breaking Changes', 21 | }, 22 | { 23 | type: 'feat', 24 | section: 'Features', 25 | }, 26 | { 27 | type: 'fix', 28 | section: 'Bug Fixes', 29 | }, 30 | { 31 | type: 'refactor', 32 | section: 'Internal', 33 | hidden: false, 34 | }, 35 | { 36 | type: 'perf', 37 | section: 'Internal', 38 | hidden: false, 39 | }, 40 | ], 41 | }, 42 | }, 43 | ], 44 | '@semantic-release/npm', 45 | '@semantic-release/changelog', 46 | [ 47 | '@semantic-release/git', 48 | { 49 | assets: ['package.json', 'package-lock.json', 'CHANGELOG.md'], 50 | message: 'chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}', 51 | }, 52 | ], 53 | '@semantic-release/github', 54 | ], 55 | } 56 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | input: 'dist-transpiled/index.js', 3 | output: [ 4 | { 5 | dir: 'dist/', 6 | entryFileNames: '[name].mjs', 7 | format: 'es', 8 | sourcemap: true, 9 | }, 10 | { 11 | dir: 'dist/', 12 | entryFileNames: '[name].cjs', 13 | format: 'cjs', 14 | generatedCode: { 15 | constBindings: true, 16 | }, 17 | interop: 'compat', 18 | sourcemap: true, 19 | }, 20 | ], 21 | external: ['keycloak-js', 'vue'], 22 | } 23 | -------------------------------------------------------------------------------- /src/composable.test.ts: -------------------------------------------------------------------------------- 1 | import { useKeycloak } from './composable' 2 | import { state } from './state' 3 | 4 | describe('useKeycloak', () => { 5 | describe('state', () => { 6 | test('should return the state values as refs', () => { 7 | const { isAuthenticated, hasFailed, isPending, token, username, roles } = useKeycloak() 8 | 9 | expect(isAuthenticated.value).toBe(false) 10 | expect(hasFailed.value).toBe(false) 11 | expect(isPending.value).toBe(false) 12 | expect(token.value).toBe('') 13 | expect(username.value).toBe('') 14 | expect(roles.value).toStrictEqual([]) 15 | }) 16 | }) 17 | describe('hasRoles', () => { 18 | test('should tell if the user has the role or not and is authenticated', () => { 19 | state.isAuthenticated = true 20 | state.roles = ['my-role', 'my-other-role'] 21 | const { hasRoles } = useKeycloak() 22 | 23 | expect(hasRoles(['my-role', 'my-other-role'])).toBe(true) 24 | expect(hasRoles(['my-role', 'not-my-role'])).toBe(false) 25 | expect(hasRoles(undefined)).toBe(false) 26 | expect(hasRoles(null)).toBe(false) 27 | }) 28 | }) 29 | describe('hasResourceRoles', () => { 30 | test('should tell if the user has the role in a resource or not and is authenticated', () => { 31 | state.isAuthenticated = true 32 | state.resourceRoles = { myApp: ['my-role', 'my-other-role'] } 33 | const { hasResourceRoles } = useKeycloak() 34 | 35 | expect(hasResourceRoles(['my-role', 'my-other-role'], 'myApp')).toBe(true) 36 | expect(hasResourceRoles(['my-role', 'not-my-role'], 'myApp')).toBe(false) 37 | expect(hasResourceRoles(['my-role', 'my-other-role'], undefined)).toBe(false) 38 | expect(hasResourceRoles(['my-role', 'my-other-role'], null)).toBe(false) 39 | expect(hasResourceRoles(undefined, undefined)).toBe(false) 40 | expect(hasResourceRoles(undefined, 'myApp')).toBe(false) 41 | expect(hasResourceRoles(null, null)).toBe(false) 42 | expect(hasResourceRoles(null, 'myApp')).toBe(false) 43 | }) 44 | }) 45 | }) 46 | -------------------------------------------------------------------------------- /src/composable.ts: -------------------------------------------------------------------------------- 1 | import type { KeycloakTokenParsed } from 'keycloak-js' 2 | import type { ShallowRef, Ref } from 'vue' 3 | import { toRefs } from 'vue' 4 | import { KeycloakInstance } from './keycloak' 5 | import { KeycloakState, keycloak, state } from './state' 6 | import { isArray, isNil } from './utils' 7 | 8 | export interface KeycloakComposable { 9 | keycloak: ShallowRef 10 | isAuthenticated: Ref 11 | hasFailed: Ref 12 | error: Ref 13 | isPending: Ref 14 | token: Ref 15 | decodedToken: Ref 16 | username: Ref 17 | userId: Ref 18 | roles: Ref 19 | resourceRoles: Ref> 20 | hasRoles: (roles: string[]) => boolean 21 | hasResourceRoles: (roles: string[], resource: string) => boolean 22 | } 23 | 24 | export const useKeycloak = (): KeycloakComposable => { 25 | return { 26 | keycloak, 27 | ...toRefs(state), 28 | hasRoles: (roles: string[]) => 29 | isArray(roles) && state.isAuthenticated && roles.every(role => state.roles.includes(role)), 30 | hasResourceRoles: (roles: string[], resource: string) => 31 | isArray(roles) && 32 | !isNil(resource) && 33 | state.isAuthenticated && 34 | !isNil(state.resourceRoles) && 35 | isArray(state.resourceRoles[resource]) && 36 | roles.every(role => state.resourceRoles[resource].includes(role)), 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/const.test.ts: -------------------------------------------------------------------------------- 1 | import { defaultInitConfig } from './const' 2 | 3 | describe('defaultInitConfig', () => { 4 | test('should have the standard config', () => { 5 | expect(defaultInitConfig.flow).toBe('standard') 6 | expect(defaultInitConfig.checkLoginIframe).toBe(false) 7 | expect(defaultInitConfig.onLoad).toBe('login-required') 8 | }) 9 | }) 10 | -------------------------------------------------------------------------------- /src/const.ts: -------------------------------------------------------------------------------- 1 | import type { KeycloakInitOptions } from 'keycloak-js' 2 | 3 | export const defaultInitConfig: KeycloakInitOptions = { 4 | flow: 'standard', 5 | checkLoginIframe: false, 6 | onLoad: 'login-required', 7 | } 8 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Keycloak comes with a client-side JavaScript library that can be used to secure HTML5/JavaScript applications. 3 | * https://www.keycloak.org/securing-apps/javascript-adapter 4 | */ 5 | 6 | export { getToken } from './keycloak' 7 | export * from './composable' 8 | export * from './plugin' 9 | -------------------------------------------------------------------------------- /src/keycloak.test.ts: -------------------------------------------------------------------------------- 1 | import { createKeycloak, getToken, initKeycloak } from './keycloak' 2 | import Keycloak from 'keycloak-js' 3 | import type { KeycloakConfig } from 'keycloak-js' 4 | import { hasFailed, isAuthenticated, isPending, setToken } from './state' 5 | import { defaultInitConfig } from './const' 6 | 7 | jest.mock('keycloak-js', () => jest.fn()) 8 | jest.mock('./state', () => { 9 | return { 10 | setKeycloak: jest.fn(), 11 | setToken: jest.fn(), 12 | hasFailed: jest.fn(), 13 | isPending: jest.fn(), 14 | isAuthenticated: jest.fn(), 15 | } 16 | }) 17 | 18 | describe('keyckoak', () => { 19 | const keycloakConfig: KeycloakConfig = { 20 | clientId: 'abc', 21 | realm: 'abc', 22 | url: 'abc', 23 | } 24 | 25 | const mockKeycloak = { 26 | token: 'abc', 27 | updateToken: jest.fn().mockImplementation(() => Promise.resolve()), 28 | init: jest.fn().mockImplementation(() => Promise.resolve(true)), 29 | } 30 | 31 | beforeEach(() => { 32 | ;(Keycloak as jest.Mock).mockClear() 33 | ;(setToken as jest.Mock).mockClear() 34 | ;(hasFailed as jest.Mock).mockClear() 35 | ;(isAuthenticated as jest.Mock).mockClear() 36 | ;(isPending as jest.Mock).mockClear() 37 | }) 38 | 39 | describe('getToken', () => { 40 | test('should return the new token', async () => { 41 | ;(Keycloak as jest.Mock).mockImplementation(() => ({ 42 | ...mockKeycloak, 43 | })) 44 | 45 | createKeycloak(keycloakConfig) 46 | const token = await getToken() 47 | 48 | expect(token).toBe('abc') 49 | }) 50 | 51 | test('should throw an error and set hasFailed to true if token could not be refreshed', async () => { 52 | ;(Keycloak as jest.Mock).mockImplementation(() => ({ 53 | token: 'abc', 54 | updateToken: jest.fn().mockImplementation(() => Promise.reject()), 55 | })) 56 | 57 | createKeycloak(keycloakConfig) 58 | 59 | await expect(getToken()).rejects.toThrow(/^Failed to refresh the access token$/) 60 | 61 | expect(hasFailed).toHaveBeenCalledWith(true, expect.any(Error)) 62 | }) 63 | }) 64 | 65 | describe('createKeycloak', () => { 66 | test('should define a new keycloak instance and return it', () => { 67 | const result = createKeycloak(keycloakConfig) 68 | 69 | expect(result.token).toBe('abc') 70 | expect(Keycloak).toHaveBeenCalledWith(keycloakConfig) 71 | }) 72 | }) 73 | 74 | describe('initKeycloak', () => { 75 | test('should set isAuthenticated to true', async () => { 76 | ;(Keycloak as jest.Mock).mockImplementation(() => ({ 77 | ...mockKeycloak, 78 | })) 79 | 80 | createKeycloak(keycloakConfig) 81 | await initKeycloak(defaultInitConfig) 82 | 83 | expect(hasFailed).toHaveBeenCalledTimes(0) 84 | expect(isPending).toHaveBeenCalledTimes(2) 85 | expect(isPending).toHaveBeenCalledWith(false) 86 | expect(isAuthenticated).toHaveBeenCalledWith(true) 87 | }) 88 | 89 | test('should set isAuthenticated to false, due to login failure ', async () => { 90 | ;(Keycloak as jest.Mock).mockImplementation(() => ({ 91 | ...mockKeycloak, 92 | token: '', 93 | init: jest.fn().mockImplementation(() => Promise.resolve(false)), 94 | })) 95 | 96 | createKeycloak(keycloakConfig) 97 | await initKeycloak(defaultInitConfig) 98 | 99 | expect(hasFailed).toHaveBeenCalledTimes(0) 100 | expect(isPending).toHaveBeenCalledTimes(2) 101 | expect(isPending).toHaveBeenCalledWith(false) 102 | expect(isAuthenticated).toHaveBeenCalledWith(false) 103 | }) 104 | 105 | test('should set isAuthenticated to false, due to invalid token', async () => { 106 | ;(Keycloak as jest.Mock).mockImplementation(() => ({ 107 | ...mockKeycloak, 108 | token: '', 109 | init: jest.fn().mockImplementation(() => Promise.reject()), 110 | })) 111 | 112 | createKeycloak(keycloakConfig) 113 | await initKeycloak(defaultInitConfig) 114 | 115 | expect(hasFailed).toHaveBeenCalledTimes(1) 116 | expect(isPending).toHaveBeenCalledTimes(2) 117 | expect(isPending).toHaveBeenCalledWith(false) 118 | expect(hasFailed).toHaveBeenCalledWith(true, expect.any(Error)) 119 | expect(isAuthenticated).toHaveBeenCalledWith(false) 120 | }) 121 | }) 122 | }) 123 | -------------------------------------------------------------------------------- /src/keycloak.ts: -------------------------------------------------------------------------------- 1 | import Keycloak from 'keycloak-js' 2 | import type { KeycloakConfig, KeycloakInitOptions } from 'keycloak-js' 3 | import { hasFailed, isAuthenticated, isPending, setKeycloak, setToken } from './state' 4 | import { isNil } from './utils' 5 | 6 | export type KeycloakInstance = Keycloak | undefined 7 | 8 | let $keycloak: KeycloakInstance = undefined 9 | 10 | async function updateToken(minValidity: number): Promise { 11 | try { 12 | await $keycloak.updateToken(minValidity) 13 | setToken($keycloak.token, $keycloak.tokenParsed) 14 | return $keycloak.token 15 | } catch (err) { 16 | const rejectionReason = isNil(err) ? new Error('Failed to refresh the access token') : err 17 | hasFailed(true, rejectionReason) 18 | throw rejectionReason 19 | } 20 | } 21 | 22 | export async function getToken(minValidity = 10): Promise { 23 | return updateToken(minValidity) 24 | } 25 | 26 | export function createKeycloak(config: KeycloakConfig): KeycloakInstance { 27 | try { 28 | $keycloak = new Keycloak(config) 29 | setKeycloak($keycloak) 30 | } catch (err) { 31 | hasFailed(true, isNil(err) ? new Error('Failed to create the keycloak adapter') : err) 32 | } 33 | return $keycloak 34 | } 35 | 36 | export async function initKeycloak(initConfig: KeycloakInitOptions): Promise { 37 | try { 38 | isPending(true) 39 | const _isAuthenticated = await $keycloak.init(initConfig) 40 | isAuthenticated(_isAuthenticated) 41 | if (!isNil($keycloak.token)) { 42 | setToken($keycloak.token, $keycloak.tokenParsed) 43 | } 44 | } catch (err) { 45 | isAuthenticated(false) 46 | hasFailed(true, isNil(err) ? new Error('Failed to initialize the keycloak adapter') : err) 47 | } finally { 48 | isPending(false) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/plugin.test.ts: -------------------------------------------------------------------------------- 1 | import { KeycloakConfig } from 'keycloak-js' 2 | import { vueKeycloak } from './plugin' 3 | import { createKeycloak, initKeycloak } from './keycloak' 4 | import { defaultInitConfig } from './const' 5 | import { state } from './state' 6 | 7 | jest.mock('./keycloak', () => { 8 | return { 9 | initKeycloak: jest.fn(), 10 | createKeycloak: jest.fn(), 11 | } 12 | }) 13 | 14 | describe('vueKeycloak', () => { 15 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 16 | let appMock: any 17 | const keycloakConfig: KeycloakConfig = { 18 | clientId: 'abc', 19 | realm: 'abc', 20 | url: 'abc', 21 | } 22 | 23 | beforeEach(() => { 24 | appMock = { 25 | config: { 26 | globalProperties: { 27 | $keycloak: undefined, 28 | }, 29 | }, 30 | } 31 | ;(createKeycloak as jest.Mock).mockClear() 32 | ;(initKeycloak as jest.Mock).mockClear() 33 | ;(createKeycloak as jest.Mock).mockImplementation(() => ({ isMyKeycloak: true })) 34 | ;(initKeycloak as jest.Mock).mockImplementation(() => undefined) 35 | jest.spyOn(console, 'error').mockImplementation(() => {}) 36 | }) 37 | 38 | test('should have error if plugin config is nil', async () => { 39 | await vueKeycloak.install(appMock) 40 | 41 | expect(state.hasFailed).toBe(true) 42 | expect(state.error.message).toBe('The VueKeycloakPluginConfig is required') 43 | }) 44 | 45 | test('should have error if keycloak config is nil', async () => { 46 | await vueKeycloak.install(appMock, {}) 47 | 48 | expect(state.hasFailed).toBe(true) 49 | expect(state.error.message).toBe('The KeycloakConfig is required') 50 | }) 51 | 52 | test('should set globalProperties', async () => { 53 | await vueKeycloak.install(appMock, { config: keycloakConfig }) 54 | 55 | expect(appMock.config.globalProperties.$keycloak).toBeDefined() 56 | expect(createKeycloak as jest.Mock).toHaveBeenCalled() 57 | expect(initKeycloak as jest.Mock).toHaveBeenCalled() 58 | }) 59 | 60 | test('should call init with the default config', async () => { 61 | await vueKeycloak.install(appMock, { config: keycloakConfig }) 62 | 63 | expect(initKeycloak as jest.Mock).toHaveBeenCalledWith(defaultInitConfig) 64 | }) 65 | 66 | test('should call init config and extend the default config', async () => { 67 | await vueKeycloak.install(appMock, { 68 | config: keycloakConfig, 69 | initOptions: { 70 | flow: 'my-flow', 71 | }, 72 | }) 73 | 74 | expect(initKeycloak as jest.Mock).toHaveBeenCalledWith({ ...defaultInitConfig, flow: 'my-flow' }) 75 | }) 76 | }) 77 | -------------------------------------------------------------------------------- /src/plugin.ts: -------------------------------------------------------------------------------- 1 | import { App, ObjectPlugin } from 'vue' 2 | import type { KeycloakConfig, KeycloakInitOptions } from 'keycloak-js' 3 | import { hasFailed } from './state' 4 | import { defaultInitConfig } from './const' 5 | import { createKeycloak, initKeycloak } from './keycloak' 6 | import { isFunction, isNil } from './utils' 7 | 8 | interface KeycloakPluginConfig { 9 | config: KeycloakConfig 10 | initOptions?: KeycloakInitOptions 11 | } 12 | 13 | type KeycloakConfigAsyncFactory = () => Promise 14 | 15 | type VueKeycloakPluginConfig = KeycloakPluginConfig | KeycloakConfigAsyncFactory 16 | 17 | export const vueKeycloak: ObjectPlugin = { 18 | install: async (app: App, options: VueKeycloakPluginConfig) => { 19 | if (isNil(options)) { 20 | hasFailed(true, new Error('The VueKeycloakPluginConfig is required')) 21 | return 22 | } 23 | 24 | let keycloakPluginConfig: KeycloakPluginConfig 25 | if (isFunction(options)) { 26 | keycloakPluginConfig = await (options as KeycloakConfigAsyncFactory)() 27 | } else { 28 | keycloakPluginConfig = options as KeycloakPluginConfig 29 | } 30 | 31 | if (isNil(keycloakPluginConfig.config)) { 32 | hasFailed(true, new Error('The KeycloakConfig is required')) 33 | return 34 | } 35 | 36 | const keycloakConfig = keycloakPluginConfig.config 37 | const keycloakInitOptions: KeycloakInitOptions = !isNil(keycloakPluginConfig.initOptions) 38 | ? { ...defaultInitConfig, ...keycloakPluginConfig.initOptions } 39 | : defaultInitConfig 40 | 41 | const _keycloak = createKeycloak(keycloakConfig) 42 | if (isNil(_keycloak)) return 43 | 44 | app.config.globalProperties.$keycloak = _keycloak 45 | 46 | await initKeycloak(keycloakInitOptions) 47 | }, 48 | } 49 | -------------------------------------------------------------------------------- /src/state.test.ts: -------------------------------------------------------------------------------- 1 | import { state, setToken } from './state' 2 | 3 | describe('state', () => { 4 | const token = 5 | 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJteS1uYW1lIiwicmVhbG1fYWNjZXNzIjp7InJvbGVzIjpbIm15LXJvbGUiXX0sInJlc291cmNlX2FjY2VzcyI6eyJteS1hcHAiOnsicm9sZXMiOlsibXktcm9sZSJdfX19.oAnF7H8DndIWOb2KeHntbzwf6h7VjZlxt5AR2KPZTBU' 6 | const tokenParsed = { 7 | sub: '1234567890', 8 | name: 'John Doe', 9 | iat: 1516239022, 10 | preferred_username: 'my-name', 11 | realm_access: { 12 | roles: ['my-role'], 13 | }, 14 | resource_access: { 15 | 'my-app': { 16 | roles: ['my-role'], 17 | }, 18 | }, 19 | } 20 | 21 | test('should have the correct inital values', () => { 22 | expect(state.isAuthenticated).toBe(false) 23 | expect(state.hasFailed).toBe(false) 24 | expect(state.error).toBe(null) 25 | expect(state.isPending).toBe(false) 26 | expect(state.token).toBe('') 27 | expect(state.username).toBe('') 28 | expect(state.roles).toStrictEqual([]) 29 | expect(state.resourceRoles).toStrictEqual({}) 30 | }) 31 | 32 | test('should update the state', () => { 33 | setToken(token, tokenParsed) 34 | 35 | expect(state.token).toBe(token) 36 | expect(state.username).toBe('my-name') 37 | expect(state.roles).toStrictEqual(['my-role']) 38 | expect(state.resourceRoles).toStrictEqual({ 'my-app': ['my-role'] }) 39 | }) 40 | }) 41 | -------------------------------------------------------------------------------- /src/state.ts: -------------------------------------------------------------------------------- 1 | import { shallowRef, reactive } from 'vue' 2 | import type { KeycloakTokenParsed } from 'keycloak-js' 3 | import { KeycloakInstance } from './keycloak' 4 | import { isString } from './utils' 5 | 6 | export interface KeycloakState { 7 | isAuthenticated: boolean 8 | hasFailed: boolean 9 | error: Error 10 | isPending: boolean 11 | token: string 12 | decodedToken: KeycloakTokenParsed 13 | username: string 14 | userId: string 15 | roles: string[] 16 | resourceRoles: Record 17 | } 18 | 19 | export const keycloak = shallowRef() 20 | 21 | export const state = reactive({ 22 | isAuthenticated: false, 23 | hasFailed: false, 24 | error: null, 25 | isPending: false, 26 | token: '', 27 | decodedToken: {} as KeycloakTokenParsed, 28 | username: '', 29 | userId: '', 30 | roles: [] as string[], 31 | resourceRoles: {}, 32 | }) 33 | 34 | export const setKeycloak = (value: KeycloakInstance): void => { 35 | keycloak.value = value 36 | } 37 | 38 | export const setToken = (token: string, tokenParsed: KeycloakTokenParsed): void => { 39 | state.token = token 40 | const content = tokenParsed 41 | state.decodedToken = content 42 | state.roles = content.realm_access ? content.realm_access.roles : [] 43 | state.username = content.preferred_username as string 44 | state.userId = content.sub 45 | state.resourceRoles = content.resource_access 46 | ? Object.fromEntries(Object.entries(content.resource_access).map(([key, value]) => [key, value.roles])) 47 | : {} 48 | } 49 | 50 | interface ErrorString { 51 | error: string 52 | } 53 | type ErrorLike = Error | ErrorString | string 54 | 55 | export const hasFailed = (value: boolean, err: ErrorLike): void => { 56 | state.hasFailed = value 57 | if (err instanceof Error) { 58 | state.error = err 59 | } else if (isString((err as ErrorString)?.error)) { 60 | state.error = new Error((err as ErrorString).error) 61 | } else if (isString(err)) { 62 | state.error = new Error(err as string) 63 | } else { 64 | state.error = new Error('Unknown') 65 | } 66 | state.error.name = '[vue-keycloak]' 67 | console.error(state.error) 68 | } 69 | 70 | export const isPending = (value: boolean): void => { 71 | state.isPending = value 72 | } 73 | 74 | export const isAuthenticated = (value: boolean): void => { 75 | state.isAuthenticated = value 76 | } 77 | -------------------------------------------------------------------------------- /src/utils.test.ts: -------------------------------------------------------------------------------- 1 | import { isArray, isFunction, isNil, isString } from './utils' 2 | 3 | describe('util', () => { 4 | const arr: unknown[] = [] 5 | const obj = {} 6 | const fun = (): void => undefined 7 | const prom = new Promise(() => undefined) 8 | const str = 'adsf' 9 | 10 | describe('isArray', () => { 11 | test('should return true if it is an Array', () => { 12 | expect(isArray(arr)).toBe(true) 13 | expect(isArray(fun)).toBe(false) 14 | expect(isArray(prom)).toBe(false) 15 | expect(isArray(obj)).toBe(false) 16 | expect(isArray(undefined)).toBe(false) 17 | expect(isArray(null)).toBe(false) 18 | expect(isArray(str)).toBe(false) 19 | }) 20 | }) 21 | 22 | describe('isFunction', () => { 23 | test('should return true if it is a valid function', () => { 24 | expect(isFunction(fun)).toBe(true) 25 | expect(isFunction(prom)).toBe(false) 26 | expect(isFunction(arr)).toBe(false) 27 | expect(isFunction(obj)).toBe(false) 28 | expect(isFunction(undefined)).toBe(false) 29 | expect(isFunction(null)).toBe(false) 30 | expect(isFunction(str)).toBe(false) 31 | }) 32 | }) 33 | 34 | describe('isNil', () => { 35 | test('should return true if it is null or undefined', () => { 36 | expect(isNil(undefined)).toBe(true) 37 | expect(isNil(null)).toBe(true) 38 | expect(isNil(fun)).toBe(false) 39 | expect(isNil(prom)).toBe(false) 40 | expect(isNil(arr)).toBe(false) 41 | expect(isNil(obj)).toBe(false) 42 | expect(isNil(str)).toBe(false) 43 | }) 44 | }) 45 | 46 | describe('isString', () => { 47 | test('should return true if it is a valid string', () => { 48 | expect(isString(str)).toBe(true) 49 | expect(isString(undefined)).toBe(false) 50 | expect(isString(null)).toBe(false) 51 | expect(isString(fun)).toBe(false) 52 | expect(isString(prom)).toBe(false) 53 | expect(isString(obj)).toBe(false) 54 | }) 55 | }) 56 | }) 57 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | export function isArray(value: unknown): boolean { 2 | return Array.isArray(value) 3 | } 4 | 5 | export function isFunction(fun: unknown): boolean { 6 | return typeof fun === 'function' 7 | } 8 | 9 | export function isNil(value: unknown): boolean { 10 | return value === undefined || value === null 11 | } 12 | 13 | export function isString(value: unknown): boolean { 14 | return typeof value === 'string' 15 | } 16 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "declaration": true, 4 | "esModuleInterop": true, 5 | "target": "es2019", 6 | "moduleResolution": "bundler", 7 | "noImplicitAny": true, 8 | "outDir": "dist-transpiled", 9 | "declarationDir": "dist/types", 10 | "removeComments": true, 11 | "sourceMap": true 12 | }, 13 | "include": ["src/**/*.ts"], 14 | "exclude": ["node_modules", "src/**/*.test.ts"] 15 | } 16 | --------------------------------------------------------------------------------