我正在尝试在 nuxt 项目中使用 Keycloak JS 进行身份验证,所以我定义了一个像这样的插件:
// plugins/keycloakjs.client.ts
import Keycloak, { KeycloakConfig } from "keycloak-js";
export default defineNuxtPlugin(_nuxtApp => {
const runtimeConfig = useRuntimeConfig();
try {
const keycloakConfig : KeycloakConfig = {
url: runtimeConfig.public.keycloakUrl,
realm: runtimeConfig.public.keycloakRealm,
clientId: runtimeConfig.public.keycloakClientId,
}
const keycloak = new Keycloak(keycloakConfig);
keycloak.init({
onLoad: "check-sso"
});
return {
provide: {
keycloak,
},
};
} catch (e) {
console.error(e)
throw createError({ statusCode: 401, message: "Keycloak error" });
}
});
我尝试在直接在 app.vue 文件中使用的导航栏组件中使用它,如下所示:
// ~/app.vue
<script setup lang="ts">
import AppNavbar from "~/components/AppNavbar.vue";
</script>
<template>
<div class="h-screen">
<app-navbar />
<NuxtPage />
</div>
</template>
最后是组件:
// components/AppNavbar.vue
<script setup lang="ts">
import Keycloak from "keycloak-js";
import { onMounted } from "vue";
const {$keycloak} = useNuxtApp()
const state = reactive({
authenticated: false,
token: null
})
onMounted( () => {
console.log('Keycloak', $keycloak)
console.log('Keycloak authenticated', $keycloak.authenticated)
if ($keycloak.authenticated) {
state.authenticated = true
state.token = $keycloak?.token
}
console.log('state', state)
})
</script>
<template>
<div class="bg-yellow p-4 flex items-center gap-3">
<button class="bg-purple p-2 rounded" @click="$keycloak.logout" v-if="state.authenticated">Logout</button>
<button class="bg-purple p-2 rounded" @click="$keycloak.login" v-else>Login</button>
<div class="bg-purple p-2 rounded w-1/2">{{ state.token }}</div>
</div>
</template>
但是当我加载应用程序时,经过身份验证的本地状态仍然为 false。记录插件值时,我将经过身份验证的值设置为 true,但在调用该属性时,它总是返回 false。请问我缺少什么?
我忘记处理 init 承诺。这是更正后的版本:
// plugins/keycloakjs.client.ts
import Keycloak, { KeycloakConfig } from "keycloak-js";
export default defineNuxtPlugin(async _nuxtApp => {
const runtimeConfig = useRuntimeConfig();
try {
const keycloakConfig : KeycloakConfig = {
url: runtimeConfig.public.keycloakUrl,
realm: runtimeConfig.public.keycloakRealm,
clientId: runtimeConfig.public.keycloakClientId,
}
const keycloak = new Keycloak(keycloakConfig);
await keycloak.init({
onLoad: "check-sso"
});
return {
provide: {
keycloak,
},
};
} catch (e) {
console.error(e)
throw createError({ statusCode: 401, message: "Keycloak error" });
}
});