how can i use const [keycloak, initialized] = useKeycloak() in react js

1.2k views Asked by At

i'm using api keycloak for authentication

     onLogin: (email, password) => {
    return dispatch => {
 
      var axios = require('axios');
      var qs = require('qs');
      var data = qs.stringify({
        'username':  email ,
        'password': password ,
        'client_id': "react",
        'grant_type': "password",
        "client_secret":"KJQplL6bo7gM6ngqlMsnjc1CfPvL2BxKm"

      
      });
      var config = {
        method: 'post',
        url:  "http://localhost:8080/auth/realms/krycloak-react-auth/protocol/openid-connect/token",
        headers: { 
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data : data
      };
      console.log(JSON.stringify(data));
      axios(config)
      .then(function (response) {
        console.log(JSON.stringify(response.data.access_token));
        const token = response.data.access_token ; 
        console.log(token);
        Axios.get("http://localhost:8080/auth/realms/krycloak-react-auth/protocol/openid-connect/userinfo",{ headers: { 'Authorization': `Bearer  ${token}`}})
        .then((response)=>{
          
              console.log(response);
             const  data = response.data;
            setTimeout(() => {
          const user = { name: data.name , email: data.email };
          dispatch(fetchSuccess());
          localStorage.setItem('user', JSON.stringify(user));
           dispatch(setAuthUser(user));
        }, 300);

        })
        .catch((err)=>{
          console.log(err);
        })

      })
      .catch(function (error) {
        console.log(error);
      });

} }

the call of constant const [keycloak, initialized] = useKeycloak()

  const {keycloak , initialized} = useKeycloak();
  useEffect(() => {
    console.log(keycloak);
  }, [])

my results keycloak  Empty

login it matches well but normally I have to see a result of keycloak like that keycloak  Blank

there is some solution for that , cause i want use the function there is into the object keycloak (LIKE : .logout() , .realaccess() ...) , if not so i need to create all api ?

0

There are 0 answers