ℹ️ The aim of this demo project is to give the reader a blueprint for using Keycloak-based authentication and authorisation in a Spring Boot app.
There are three different ways to protect a Spring Boot app using Keycloak that we are going to investigate.
- Use the Spring Boot adapter
- Use the Spring Security adapter
- Use Gatekeeper
You need a running kubernetes cluster.
It should work on both minikube
or k3s
.
kubectl apply -f keycloak
sudo echo "127.0.0.1 keycloak.keycloak.svc" >> /etc/hosts
kubectl port-forward <KEYCLOAK_POD_NAME> 8180:8180 -n keycloak
If you're using IntelliJ (as you should ;-) you will find some *.http files in src/test/resources
that you can use to test whether authentication works as expected.
- Run
greet.http
and you should get a polite but resolute401 (Unauthorized)
. - Run
authenticate.http
and copy the contents ofaccess_token
- Put the token after
Bearer
in thegreet.http
and run it again. - 🎉
setgreeting.http
requires the role 'edit', so we have to login with the gsadmin
user.
Otherwise you will get a passive aggressive but expressive 403 (Forbidden)
.
This way you can test the different integrations of Keycloak. Have fun and stay safe!
https://www.keycloak.org/docs/latest/securing_apps/index.html#_spring_boot_adapter
The configuration for the Spring Boot adapter can be found in the branch springboot-adapter
.
Just start the app with the main class (RestServiceApplication
) from your IDE.
https://www.keycloak.org/docs/latest/securing_apps/index.html#_spring_security_adapter
The configuration for the Spring Boot adapter can be found in the branch springsecurity-adapter
.
Just start the app with the main class (RestServiceApplication
) from your IDE.
https://www.keycloak.org/docs/latest/securing_apps/index.html#_javascript_adapter
The frontend consists of a VueJs application which uses the keycloak-js adapter.
The application forwards to keycloak for the user to authenticate.
It then uses the acquired access_token
to call the greeting
service.
The configuration for gatekeeper is in the master
branch.
As gatekeeper runs as a sidecar container along the greetingservice, you have to run the service in the kubernetes cluster.
In the rest
directory:
mvn compile jib:dockerBuild
kubectl apply -f k8s
The service is then available at http://localhost:30080
(see greet.http
and setgreeting.http
).
Let's explore another great feature of gatekeeper, namely forward-signing requests. You can attach gatekeeper to any service that you wish to grant authentication to a given service.
Ok, slowly. We have our greeting
service that is guarded by gatekeeper.
Now we have another service, called reverse
that needs access to the greetingservice
.
We could either
- build authentication in the
reverse
service or - Use gatekeeper.
In this usecase gatekeeper acts as a proxy that automatically fetches the access_token
from keycloak and fill the Authorization
header.