Initialize Svelte application based on promise
P粉872101673
P粉872101673 2023-09-01 09:35:33
0
1
568
<p>I have previously developed several Vue applications that used Keycloak for authentication and authorization. For Vue applications, Keycloak provides a solution to ensure that unauthenticated users cannot load Vue applications by only initializing the application when the user is authenticated. </p> <pre class="brush:js;toolbar:false;">keycloak.init({ onLoad: initOptions.onLoad }).then((auth) => { if (!auth) { window.location.reload(); } else { Vue.$log.info("Authenticated"); newVue({ el: '#app', render: h => h(App, { props: { keycloak: keycloak } }) }) } ... </pre> <p>Now, I'm working on a Svelte project and I want to apply the same approach. Is there a way to initialize a Svelte application based on Promises, similar to how it is done in Vue using Keycloak? </p> <p>I've tried looking for a solution but I can't find anything specifically addressing this issue for Svelte. </p> <p>The biggest advantage to me is that you are always 100% sure that the user is authenticated and you always have access to the JWT token to send to the backend when necessary. </p>
P粉872101673
P粉872101673

reply all(1)
P粉724256860

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)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template