Keycloak Tutorial: Logins Your Shop Controls Itself
Quick answer
Keycloak is a free, open source identity server that handles logins, users, and tokens for your apps, so you stop writing password code yourself. You run it on your own server, create a realm for your project, add a client for each app, and add users. This post runs Keycloak 26.8.2 locally and proves the login works with a real token.
A small clothing shop in Karachi keeps its orders in a dashboard. At first one person knows the password, and it works. Then a second staff member joins, then a third, and the shared password starts travelling around on WhatsApp. Nobody can tell who changed an order, and when someone leaves, the password has to change for everyone. The shop needs a login system where each person has their own account and the dashboard checks a token instead of trusting a shared secret. That is what Keycloak does, and it runs on your own hardware.
What I would check before using it
My first check is how many apps will share the login. Keycloak pays off when one login serves several things at once, a dashboard, an admin panel, a customer site, with every app trusting the same server. For a single small app with two users, the login your framework already ships is less moving parts.
My second check is who looks after the server. Keycloak is a Java application with its own database, needing updates, backups, and someone who notices when it stops. If nobody will own it, a hosted identity provider, where someone else patches the server, may be safer even though it costs money.
My third check is whether your apps speak the same language. Keycloak issues tokens using OpenID Connect, the standard most modern frameworks understand, and the JWT Authentication: Verify a Token Without a Database post explains how those tokens work once they reach your API. If an app only understands its own session cookies, you will write an adapter, and that erases much of the saving.
My fourth check is what the roles look like. Keycloak stores roles and groups, but you still decide the rules: who can change an order, who can only read one, what happens when someone leaves.
My verdict, as judgement: adopt Keycloak when one login serves several apps and someone keeps the server updated. It flips for a single small app, or when nobody owns the server.
A Karachi clothing shop, logging in through Keycloak
The demo is the Karachi clothing shop from the intro, where staff member Sana Malik needs her own login for the orders dashboard.
Download Keycloak 26.8.2 and start it in dev mode:
$ curl -L -o keycloak-26.8.2.zip https://github.com/keycloak/keycloak/releases/download/26.8.2/keycloak-26.8.2.zip
$ unzip -q keycloak-26.8.2.zip
$ export JAVA_HOME=$HOME/workspace/.toolchains/jdk-21.0.13+9
$ export KC_BOOTSTRAP_ADMIN_USERNAME=admin
$ export KC_BOOTSTRAP_ADMIN_PASSWORD=admin123
$ keycloak-26.8.2/bin/kc.sh start-dev --http-port=8080
Keycloak 26.8.2 on JVM (powered by Quarkus 3.40.1.1) started in 36.356s. Listening on: http://localhost:8080
Keycloak organises everything into realms. Get an admin token from the built-in master realm, save it as ADMIN_TOKEN, then create a realm called shop:
$ curl -s -X POST http://localhost:8080/realms/master/protocol/openid-connect/token \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'username=admin' -d 'password=admin123' \
-d 'grant_type=password' -d 'client_id=admin-cli'
$ curl -s -o /dev/null -w "HTTP %{http_code}\n" -X POST http://localhost:8080/admin/realms \
-H "Authorization: Bearer $ADMIN_TOKEN" -H 'Content-Type: application/json' \
-d '{"realm":"shop","enabled":true,"displayName":"Karachi Clothing Shop"}'
HTTP 201
Next, a client: one app talking to Keycloak, here the orders dashboard. It is confidential, so it has a secret, and direct access grants are on:
$ curl -s -o /dev/null -w "HTTP %{http_code}\n" -X POST http://localhost:8080/admin/realms/shop/clients \
-H "Authorization: Bearer $ADMIN_TOKEN" -H 'Content-Type: application/json' \
-d '{"clientId":"orders-dashboard","enabled":true,"publicClient":false,"directAccessGrantsEnabled":true,"standardFlowEnabled":true,"redirectUris":["http://localhost:3000/*"]}'
HTTP 201
Save the client secret as $SECRET, create Sana, and set her password:
$ SECRET=$(curl -s http://localhost:8080/admin/realms/shop/clients/582e65bf-9d8f-41de-afdd-059ba51840dc/client-secret \
-H "Authorization: Bearer $ADMIN_TOKEN" | python3 -c 'import sys,json; print(json.load(sys.stdin)["value"])')
$ curl -s -o /dev/null -w "HTTP %{http_code}\n" -X POST http://localhost:8080/admin/realms/shop/users \
-H "Authorization: Bearer $ADMIN_TOKEN" -H 'Content-Type: application/json' \
-d '{"username":"sana","enabled":true,"firstName":"Sana","lastName":"Malik","email":"sana@shop.example"}'
HTTP 201
$ curl -s -o /dev/null -w "HTTP %{http_code}\n" -X PUT http://localhost:8080/admin/realms/shop/users/66408052-210f-468f-923c-56120a4506d1/reset-password \
-H "Authorization: Bearer $ADMIN_TOKEN" -H 'Content-Type: application/json' \
-d '{"type":"password","value":"ShopStaff123","temporary":false}'
HTTP 204
Now Sana logs in: the password grant trades her username, password, and the client secret for a token. My first attempt used the wrong secret, and Keycloak refused it plainly:
$ curl -s -X POST http://localhost:8080/realms/shop/protocol/openid-connect/token \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'username=sana' -d 'password=ShopStaff123' \
-d 'grant_type=password' -d 'client_id=orders-dashboard' -d 'client_secret=wrong-secret'
{"error":"unauthorized_client","error_description":"Invalid client or Invalid client credentials"}
HTTP 401
With the real secret:
$ curl -s -X POST http://localhost:8080/realms/shop/protocol/openid-connect/token \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'username=sana' -d 'password=ShopStaff123' \
-d 'grant_type=password' -d 'client_id=orders-dashboard' -d 'client_secret=$SECRET'
token_type: Bearer
expires_in: 300
scope: profile email
The token is a JWT. Decoding its middle part shows preferred_username sana and name Sana Malik, under issuer http://localhost:8080/realms/shop: a signed token for one named person.
Then the instructive failure: I called userinfo with that token, and got a 403 with an empty body:
$ curl -s http://localhost:8080/realms/shop/protocol/openid-connect/userinfo \
-H "Authorization: Bearer $ACCESS"
HTTP 403
The header gave the reason: error="insufficient_scope", error_description="Missing openid scope". The token was valid but lacked the openid scope, so the fix is to ask for that scope:
$ curl -s -X POST http://localhost:8080/realms/shop/protocol/openid-connect/token \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'username=sana' -d 'password=ShopStaff123' \
-d 'grant_type=password' -d 'client_id=orders-dashboard' -d 'client_secret=$SECRET' \
-d 'scope=openid profile email'
scope: openid profile email
expires_in: 300
With the new token:
$ curl -s -w "\nHTTP %{http_code}\n" http://localhost:8080/realms/shop/protocol/openid-connect/userinfo \
-H "Authorization: Bearer $ACCESS"
{"sub":"66408052-210f-468f-923c-56120a4506d1","email_verified":false,"name":"Sana Malik","preferred_username":"sana","given_name":"Sana","family_name":"Malik","email":"sana@shop.example"}
HTTP 200
With no token at all, the same endpoint refuses:
$ curl -s -w "\nHTTP %{http_code}\n" http://localhost:8080/realms/shop/protocol/openid-connect/userinfo
HTTP 401
A valid token gets in, no token does not, and the wrong scope gets a 403. The dashboard can now trust Keycloak to answer "who is this?" instead of keeping a password.
Common mistakes and how to fix them
First, the wrong client secret. The symptom is a 401 with {"error":"unauthorized_client","error_description":"Invalid client or Invalid client credentials"}. The fix is to fetch the secret again from the Admin API and paste it exactly.
Second, a token without the openid scope, used on userinfo. The symptom is a 403 with an empty body and a header saying error="insufficient_scope". The fix is to add scope=openid profile email to the token request.
Third, a protected endpoint called with no token. The symptom is a plain 401. The fix is to send Authorization: Bearer $ACCESS, and to request a fresh token when the old one expires.
Fourth, an expired token. The token here lasts 300 seconds, five minutes, and after that the same calls return 401. The fix is to use the refresh token to ask for a new access token, instead of asking Sana to type her password again.
Fifth, a public client, or direct access grants left off, when the flow needs a secret. The symptom is a 401 saying the client is not allowed for that grant. The fix is to set publicClient to false and directAccessGrantsEnabled to true.
Frequently Asked Questions
Do I need Docker to run Keycloak? No. The zip download plus Java 21 is enough, as this post shows.
Is Keycloak free? Yes, it is open source under the Apache 2.0 licence. You still pay for the machine it runs on and the time to look after it.
Can Keycloak replace the JWT code in my API? It replaces the login and token issuing, not the checking. Your API still verifies the token on every request, as the JWT Authentication: Verify a Token Without a Database post shows.
How long does a token last? Five minutes by default, shown here as expires_in: 300. A stolen token stops working quickly, and the refresh token gets a new one.
Should the password grant be used in a real app? Only for first-party apps you fully control, like a staff dashboard. For anything users open in a browser, use the authorisation code flow with PKCE instead.
What to remember
- A realm is the boundary: one realm per project.
- A client is one app; a confidential client has a secret that must match exactly.
- A token proves who signed in, and its scope decides which endpoints accept it.
- A 401 means bad credentials or token; a 403 means a valid token without the scope.
- Tokens last five minutes by default, so plan for refresh, not for re-login.
Where this leaves you
One download, one realm, one client, one user, and the shop has logins it controls: Sana signs in with her own password, Keycloak hands her a token, and the dashboard checks it instead of a password shared on WhatsApp. The 403 was the useful part: a valid token is not a blank cheque, and scope opens each door. Take one app of your own that still shares a password, give it a realm, and let Keycloak answer who is signing in.
Further reading
- Keycloak getting started with the zip distribution
- Keycloak Server Administration Guide
- Keycloak Quickstarts: example apps that secure logins with Keycloak
- JWT Authentication: Verify a Token Without a Database
- Django REST Framework Tutorial: A Real Shop Orders API
- Postman Explained: Testing APIs Before the Frontend Exists
- FastAPI Explained: Python APIs at Full Speed
Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.
Comments
Post a Comment