Vuecloak uses the official Keycloak JS Adapter.
npm i -S vuecloak
yarn add vuecloak
It is mandatory to provide a config object containing your Keycloak url, realm and clientId.
import { Vuecloak } from 'vuecloak'
app
.use(Vuecloak, {
config: {
url: 'KEYCLOAK_URL',
realm: 'KEYCLOAK_REALM',
clientId: 'KEYCLOAK_CLIENT_ID'
}
})
You can provide custom initialization options to Keycloak adapter through init property.
app
.use(Vuecloak, {
init: {
onLoad: 'login-required',
checkLoginIframe: false
}
})
Vuecloak allows you to listen to Keycloak callback events.
Key | Type |
---|---|
onReady |
Function(keycloak) |
onAuthSuccess |
Function(keycloak) |
onAuthError |
Function(keycloak) |
onAuthRefreshSuccess |
Function(keycloak) |
onAuthRefreshError |
Function(keycloak) |
onAuthLogout |
Function(keycloak) |
onTokenExpired |
Function(keycloak) |
onInitSuccess |
Function(authenticated) |
onInitError |
Function(error) |
You can use this way:
app
.use(Vuecloak, {
onReady (keycloak) {
...
},
onInitSuccess (authenticated) {
...
},
})
Vuecloak adds a $keycloak property with its properties and methods to global Vue instance for you to use within your templates.
<template>
<button @click="$keycloak.logout">
Logout
</button>
</template>
You can add $keycloak instance to your Vue setup too using inject option.
import { inject, onBeforeMount } from 'vue'
export default {
setup () {
const keycloak = inject('$keycloak')
onBeforeMount(() => {
keycloak.loadUserInfo()
.then((user) => {
...
})
})
}
})
Vuecloak has no strategy for keeping your tokens valid, so you need to do this on your own. A good way is to check it before API calls.
axios.interceptors.request.use(async config => {
await app.config.globalProperties.$keycloak.updateToken()
config.headers.common.Authorization = `Bearer ${app.config.globalProperties.$keycloak.token}`
return config
})
app
.use(Vuecloak, {
config: {
url: 'KEYCLOAK_URL',
realm: 'KEYCLOAK_REALM',
clientId: 'KEYCLOAK_CLIENT_ID'
},
init: {
onLoad: 'login-required',
checkLoginIframe: false
},
onReady (keycloak) {...},
onAuthSuccess (keycloak) {...},
onAuthError (keycloak) {...},
onAuthRefreshSuccess (keycloak) {...},
onAuthRefreshError (keycloak) {...},
onAuthLogout (keycloak) {...},
onTokenExpired (keycloak) {...},
onInitSuccess (authenticated) {...},
onInitError (error) {...},
})
Vuecloak uses the power of Vue Devtools to provide a great developer experience.
Only available in Vue Devtools 6+