In this blog, we’ll look at how to set up Keycloak as an OAuth2 Authorization Server and use Java as the OAuth2 Resource Server. Keycloak will generate JWTs and provide a JWKS endpoint, while Java will validate the tokens using this JWKS endpoint to control access to APIs.
This is basically our architecture (I was too lazy to draw the lines). But if we use our brains, we can imagine these lines going from the backend to keycloak, and then to the corresponding authentication providers (Microsoft, Google and Apple).
“So … LETS COMMENCE!” - A Programming God
Just like a meal prep, we need a few ingredients in our basket to create our meal prep named Keycloak, which will act as our OAuth2 Authorization Server. This means that Keycloak is going to handle JWT creation and exposure through its provided endpoints—instead of us doing it ourselves through our backend.
Based on these ingredients, we can already see some interesting things. We are going to use our backend as the Keycloak communication layer instead of letting the frontend communicate directly with Keycloak—which is very bad practice, by the way.
We will create endpoints in our backend for our frontend, e.g., /v1/roles
with a GET endpoint to retrieve roles.
All these roles will be created in our backend in an enum named Role
By the way: Since we don’t have that many roles in our application, it’s just easier to hardcode the roles in Java instead of doing something crazy like having an adapter that continuously syncs roles in Keycloak with Java. Just copying and pasting the roles defined in Keycloak into Java is the preferred solution in our case.
Another thing we need to understand is realms, groups, and users in Keycloak.