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.
Login Function
Keycloak documentation provides information how to do client-side authentication using its Javascript adapter. According to the documentation, this is how to use Keycloak:
|
|
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.
Logout Function
Implementing logout function is similar with login. I have to use the same keycloak
object defined in the +layout.ts
file.
|
|
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.
|
|
This will log the user out of Tabunganku after displaying the logout notification for 3 seconds.
Passing Keycloak Token
To read user data in the backend, we need to include Keycloak token in the header request.
|
|
In this snippet, the system extracts the token value from the kc-cookie
cookie and puts it in the Authorization
header.