Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Keycloak as Authorization Server with Zuul as API Gateway

I'm currently building a microservice backend with Spring Boot, Zuul as API Gateway and Keycloak as Authentication and Identity Provider. For my frontend I'm currently using Angular as an SPA with the Authorization Code Grant. The API Gateway should validate each request (if the user is authorized) via Keycloak before sending it to the microservice. Each microservice ( ResourceServer) should be able to get the user information for the current request by using the introspection endpoint.

What would be the correct way to implement this, or is this even a bad design and I'm on the wrong way?

like image 874
Hiighsky Avatar asked Oct 20 '25 13:10

Hiighsky


1 Answers

Typically, you have two options:

  1. JWT given to client: The client (Angular SPA in your case) authenticates and receives the JWT. The JWT token can be verified by an party using the Keycloak public key. It also contains a lot of user information.

  2. JWT given to back-end: The client is given the temporary authorization code grant. It is forwarded to a backend system, which exchange it for the JWT. The backend system will need to create a user session, store the JWT in the user session and use a session ID cookie (or a similar mechanism) to match the client to the session.

The proposed architecture is a mix of both worlds. Option 1 would be more natural.

  • Option 1: The client authenticates with Keycloak and gets the JWT. It then attaches the JWT to each request. Zuul can check that the JWT is signed by the trusted Keycloak instance and that it has not yet expired (without contacting Keycloak). The microservice can do the same. If more than the basic user information is needed, the microservice can contact Keycloak.

  • Option 2: I can't tell you if option 2 is possible with Zuul. Let's assume that it is. If so, the gateway would redirect unauthenticated requests to Keycloak. Once the client has received the authorization code grant, it is redirected to the API gateway. The API gateway then contacts Keycloak to exchange the code for the JWT and saves it in a session. The client is given a session ID. When a request is forwarded to the micro service, the JWT is added to the request. The client never sees the JWT.

These descriptions assume that you are using Open ID Connect, which is supported by Keycloak. If you use an OAuth 2 setup, most things still apply but a few details are more complicated, e.g. instead of the JWT containing all the information you get an opaque token that can only be validated against an introspection endpoint.

like image 99
Codo Avatar answered Oct 22 '25 01:10

Codo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!