In the previous version of Tabunganku, we had to manually put user data into the database to use Tabunganku. The process was complicated, and the application can only be used by one person. In the new version, Keycloak handles user management in the new version. This is how I implement Keycloak for a Svelte application.
Keycloak documentation provides information how to do client-side authentication using its Javascript adapter. According to the documentation, this is how to use Keycloak:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
importKeycloakfrom'keycloak-js';constkeycloak=newKeycloak({url:'http://keycloak-server${kc_base_path}',realm:'myrealm',clientId:'myapp'});try{constauthenticated=awaitkeycloak.init();console.log(`User is ${authenticated?'authenticated':'not authenticated'}`);}catch(error){console.error('Failed to initialize adapter:',error);}
It imports Keycloak class from keycloak-js library, instantiate a Keycloak object, and call its init function. The keycloak variable declared here will try to connect to a realm named myrealm using a client myapp. What is a realm and a client? In Keycloak, a realm functions as a space where you can store users, roles, and groups, while a client serves as an identifier for an entity connecting to the specified realm. An entity can be anything, from a simple REST API to a mobile application.
To secure the application and allow access only to authenticated users, I use Svelte’s layout file to instantiate a Keycloak object. A layout file allows child pages to reuse resources that have been defined in the layout.
In the snippet above, load function instantiates a new Keycloak object with the parameters defined by instance and kcInitOpts variables, returning keycloakPromise—a Promise object from the init function that can be used in +layout.svelte. If Keycloak is successfully initialized, it will store a token in cookie named kc-cookie.
In +layout.svelte, it imports the keycloak variable defined in +layout.ts file and checks if Keycloak has been started. The page will reload if not, and after the reload, a login page will appear.
When the logout page is loaded, it will call await parent(), which will return data defined on the parent page(layout page). After retreiving the keycloak object, I pass it to the +logout.svelte page and call the logout function from there.