P粉7242568602023-09-02 07:57:11
When using Svelte alone, you can use Client-side component API
import App from "./App.svelte" keycloak.init({ onLoad: initOptions.onLoad }).then((auth) => { if (!auth) { window.location.reload(); } else { new App({ target: document.getElementById('#app'), props: { keycloak: keycloak } }) }) }
In a SvelteKit application, you can add global behavior using src/routes/layout.js:
// layout.js import { browser } from "$app/environment"; /** * @type {import('./$types').LayoutLoad} */ export const load = async () => { let keycloakPromise; if (browser) { keycloakPromise = keycloak.init({ onLoad: initOptions.onLoad }).then((auth) => { if (auth) { return keycloak; } }); } return { keycloak: keycloakPromise, }; };
<!-- layout.svelte -->
<script>
import { onMount } from "svelte";
/** @type {import('./$types').LayoutData} */
export let data;
onMount(() => {
if (!data.keycloak) {
window.location.reload();
}
});
</script>
{#if data.keycloak}
<slot />
{/if}
Authentication fails when data.keycloak
is not defined.
This allows conditional rendering of content.
(code example assumes keycloak is client authentication)