ivangfr / springboot-react-keycloak

The goal of this project is to secure movies-app using Keycloak (with PKCE). movies-app consists of two applications: one is a Spring Boot Rest API called movies-api and another is a React application called movies-ui.
398 stars 156 forks source link

How to create user extra after first time login keycloak? #5

Closed shalahuddinn closed 3 years ago

shalahuddinn commented 3 years ago

First, thank you for the code. It really helps me. Sorry if this is a newbie question. I've tried to understand how do you create the user extra such avatar after login at keycloak but I still don't understand. Can you explain a little bit?

ivangfr commented 3 years ago

Hi @shalahuddinn

The code you are talking about is here https://github.com/ivangfr/springboot-react-keycloak/blob/master/movies-ui/src/App.js#L24

  ...
  const handleOnEvent = async (event, error) => {
    if (event === 'onAuthSuccess') {
      if (keycloak.authenticated) {
        let response = await moviesApi.getUserExtrasMe(keycloak.token)
        if (response.status === 404) {
          const userExtra = { avatar: keycloak.tokenParsed.preferred_username }
          response = await moviesApi.saveUserExtrasMe(keycloak.token, userExtra)
          console.log('UserExtra created for ' + keycloak.tokenParsed.preferred_username)
        }
        keycloak['avatar'] = response.data.avatar
      }
    }
  }
  ...

In short, it's listening to some events and just onAuthSuccess event is handled. If the user is authenticated, a GET call is submitted to moviesApi (/api/userextras/me endpoint). If a 404 is returned, an extraUser record is saved in moviesApi.

ivangfr commented 3 years ago

Hey @shalahuddinn , did you get it? Can I close this issue?

ivangfr commented 3 years ago

Hi @shalahuddinn , I am closing this issue. I hope you have implemented what you would like to.