I have a very simple react app and I want to add keycloak authentication to it's pages. I'm using following versions
- react v18
- keycloak 18.0.0 (with quarkus)
- react-keycloak/web: 3.4.0
- keycloak-js: 20.0.3
- react-router-dom: 6.8.1
These are my classes
index.tsx
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
// <React.StrictMode>
<App />
// </React.StrictMode>
);
reportWebVitals();
App.tsx
import { BrowserRouter, Route, Routes } from "react-router-dom";
import HomePage from "./pages/Homepage";
import keycloak from "./Keycloak"
import { ReactKeycloakProvider } from "@react-keycloak/web";
import './App.css';
function App() {
return (
<ReactKeycloakProvider authClient={keycloak} initOptions={{ onLoad: "login-required" }}>
<BrowserRouter>
<Routes>
<Route path="/" element={<HomePage />} />
</Routes>
</BrowserRouter>
</ReactKeycloakProvider>
);
}
export default App;
Keycloak configs
import Keycloak from "keycloak-js";
const keycloak = new Keycloak({
url: "http://localhost:8180",
realm: "Demo",
clientId: "react-app",
});
export default keycloak;
HomePage.tsx
import { useKeycloak } from "@react-keycloak/web";
import { useState, useEffect } from "react";
const Home = () => {
const { keycloak } = useKeycloak();
const [isLoggedIn, setIsLoggedIn] = useState(false)
useEffect(()=>{
setIsLoggedIn(keycloak.authenticated || false)
}, [keycloak])
console.log("-----------is logged in:", isLoggedIn)
return isLoggedIn ? <h1 className="text-green-800 text-4xl">Welcome</h1>
: <div>{`User is NOT authenticated`}</div>;
};
export default Home;
After I npm start and go to home page even I get keycloak login page.
But after login with correct credentials following page is shown. This page is shown when keycloak.authenticated is false.
I really appreciate if anyone can figure out why I'm not authenticated even after successful login.
github url: https://github.com/ruchiranawarathna/react-with-keycloak-auth
change the object passed to the Keycloak constructor to have these parameters
OR you can as well click on
Download adapter config
from theaction
buttton dropdown in this screenshot and use the generated json object