Example for Keycloak auth with SvelteKit, Go api and Postgres db
Configuration
All is handled via .env files one at web specifically and another one at root folder for the rest of the components.
Auth server will provide a token for web app, where the user has role(s) associated for this clientId.
/.env – used by keycloak, api and postgres.
/web/.env – used by web app
In order to expose them via vite look at the following files
/web/src/vite-env.d.ts
/web/src/lib/variables.ts
The env settings values are used here:
/web/src/lib/components/auth/Auth.ts
/web/src/lib/components/auth/Registry.ts
docker-compose.yml creates one docker container go-keycloak that will run postgres db and keycloak server you will notice their names ending with -1 as it can be managed by kubernetes by expanding/contracting number of instances.
Compiling the project
Clone this repo from https://github.com/sainzg/go-keycloak
In a command prompt run the following
docker-compose build
Running the project
In order to run this project open three different command prompts and execute the following commands in each window.
1. Keycloak server, postgres db, go api, sveltekit/node web app
Start container: docker-compose up
Stop container: docker-compose down
All 4 components should be running now
Keycloak auth server
login credential admin / admin
Postgres db
jdbc:postgres://localhost:5432/pulsar-tfm-auth
login credential postgres / password
Api (GO) – http://localhost:8086
Web (SvelteKit) – http://localhost:3000
3. Create a user in Keycloak auth server to use it from the web app and api
Login to http://localhost:8080 using admin/admin
Create a user.
Assign it to the [dev] group.
Set a password.
4. Web app
Login with the user created in step 4.
Access the secured page http://localhost:3000/secured
Click on count button to see the counter incrementing once authenticated
Note: go api counter is not thread-safe as it is just an example for auth.