Initialize Svelte application based on promise
P粉872101673
2023-09-01 09:35:33
<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>
When using Svelte alone, you can use Client-side component API
In a SvelteKit application, you can add global behavior using src/routes/layout.js:
Authentication fails when
data.keycloak
is not defined. This allows conditional rendering of content.(code example assumes keycloak is client authentication)