I follow these steps (https://scalac.io/user-authentication-keycloak-1/) to authenciate my react app with keycloak. But one small different thing here is that I am using react hook to manage my state(the code below). That causes the page reload again and again. Do you have any idea?
import React, { useState, useEffect } from "react";
import UserInfo from "./UserInfo";
import Logout from "./Logout";
import Keycloak from "keycloak-js";
// The difference is here
function Secured(props) {
const [keycloak, setKeycloak] = useState(null);
const [isAuthenciated, setAuthenciation] = useState(false);
useEffect(() => {
const keycloak = Keycloak("/keycloak.json");
keycloak.init({ onLoad: "login-required" }).then(authenticated => {
setKeycloak(keycloak);
setAuthenciation(authenticated);
});
});
if (keycloak) {
if (isAuthenciated)
return (
<div>
<p>
This is a Keycloak-secured component of your application. You
shouldn't be able to see this unless you've authenticated with
Keycloak.
</p>
<UserInfo keycloak={this.state.keycloak} />
<Logout keycloak={this.state.keycloak} />
</div>
);
else return <div>Unable to authenticate!</div>;
}
return <div>Initializing Keycloak...</div>;
}
export default Secured;
It seems like you forgot to include the dependencies of useEffect. Not setting them makes useEffect to run on every render. In case you only want it to run once we set the dependencies as an empty array.
useEffect(() => {
const keycloak = Keycloak("/keycloak.json");
keycloak.init({ onLoad: "login-required" }).then(authenticated => {
setKeycloak(keycloak);
setAuthenciation(authenticated);
});
}, []);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With