Home > Net >  Spring Boot Oauth2 Redirect to Keycloack Login Page for Authentication Or Generate Access Token in A
Spring Boot Oauth2 Redirect to Keycloack Login Page for Authentication Or Generate Access Token in A

Time:12-12

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?

CodePudding user response:

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)

  • Related