@jabardigitalservice/nuxt-module-keycloak v0.0.1
@jabardigitalservice/nuxt-module-keycloak
Pluggable NuxtJS module for Keycloak SSO functionality.
Features
- Dynamic vuex module registration under user-defined
namespace
. - Inject Keycloak instance into Nuxt context.
- Auto-register middleware for Keycloak initiation, authentication, and refresh token. Middleware can either be used globally, per layout, or per route.
Available Options
Options can be set inside module definition in nuxt.config.js
or by using corresponding .env
keys.
| Name or .env
key | Type | Attribute | Default | Description |
| --- | --- | --- | --- | ---- |
| keycloakUrl, KEYCLOAK_URL | string | | | Keycloak auth URL in which authentication is performed. |
| redirectUri, KEYCLOAK_REDIRECT_URL | string | | | Application URL to be redirected onto after authentication is performed and validated by keycloak. |
| realm, KEYCLOAK_REALM | string | | | Keycloak realm. |
| clientId, KEYCLOAK_CLIENT_ID | string | | | Keycloak client ID. |
| refreshInterval, KEYCLOAK_INTERVAL | number | optional | 60000 | Keycloak refresh token interval in milliseconds. |
| namespace, KEYCLOAK_NAMESPACE | string | optional | keycloak | Keycloak nuxt module namespace. Used as middleware name, vuex module namespace, and injected context property name. |
How to use
Go to root folder of your Nuxt project and install this package.
yarn add @jabardigitalservice/nuxt-module-keycloak # using NPM npm install @jabardigitalservice/nuxt-module-keycloak
Assign module in nuxt.config.js
export default { modules: [ ['@jabardigitalservice/nuxt-module-keycloak', { namespace: 'keycloak', refreshInterval: 60000, clientId: KEYCLOAK_CLIENT_ID, realm: KEYCLOAK_REALM, keycloakUrl: 'https://your-keycloak-domain.app', redirectUri: 'https://your-webpage.app', }] ] }
Assign configured
namespace
as middleware value.// set globally in nuxt.config.js export default { router: { middleware: ['keycloak'] } } // or in layout, e.g layout/default.vue export default { middleware: ['keycloak'] } // or in page, e.g pages/index.vue export default { middleware: ['keycloak'] }
Injected property/context/module
- Use
this.$keycloak
(orthis.$<namespace>
) to access Keycloak instance.// inside Vue component export default { methods: { logout () { return this.$keycloak.logout() } } }
Injected instance can also be accessed using Nuxt context. Note: property name is based on
namespace
option.// inside your nuxt plugin, e.g plugins/some-fn.js export default (context) => { const keycloak = context.$keycloak; } // shorthand export default ({ $keycloak }) => {}
Keycloak Vuex module is registered under
namespace
.// inside Vue component export default { computed: { ...mapState('keycloak', [ 'user', 'roles', 'permissions' ]) } }
Caveats
Ensure your store
folder at least consist index.js
, since Vuex would only be initiated by Nuxt using this way.
4 years ago