Spring Boot Oauth2 Redirect to Keycloack Login Page for Authentication Or Generate Access Token in API Gateway with Keycloak Token Creation Post API


I am implementing OAuth2 (Keycloak) for our application. Our Application is combined of multiple Microservices (Rest APIs) and also there is an UI which calls the APIs. We have a API Gateway (Zuul) where we want to implement the Spring Boot OAuth2 with Keycloak.

After checking on the internet I can see there are 2 options while implementing OAuth2 (Keycloak) in Spring Boot.

  1. I can redirect the user to Keycloak Login page when the user is not authenticated. Once the User is authenticated with Keycloak, then the user can access the APIs with the access token which it will get from the Keycloak Auth server.

  2. Instead of Keycloak Login page, I can have my Own Login Page in UI and once the user submits their username & password, the details come to my API Gateway (Spring Boot code – Zuul) and with the given username & password, I can get a access token from Keycloak with their (keycloak) Token Creation POST API and send back the Access Token to the user in the Response Header along with the HOME Page and user will able to use that token for further API calls until the token gets expired.

Which option is better to use? Login with Redirect to Keycloak Login page to get the access token or Calling Keycloak POST API for token creation from Spring Boot App?


For user authentication, use authorization code flow => first option.

First option is safer: your app is never aware of user password and, as so, can’t leak it.

First option is also more future proof: if the number of clients increases and authentication requirements evolves (multi factor authentication for instance), then this is handled once on the authorization-server. Same for user registration.

If you are connected about the look and feel, refer to Keycloak doc. You’ll find how to provide your own style and even template.

Last, use an OIDC client library on your client to ease authorization-code flow on your client: spring-boot-starter-oauth2-client if it’s a Spring app serving content with Thymeleaf, JSF, etc. Or a lib like what angular-auth-oidc-client is to Angular (search an equivalent for your own framework)

Answered By – ch4mp

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published