App.js
import { useKeycloak } from "@react-keycloak/web"
const { initialized } = useKeycloak()
if (!initialized) {
return <h3>Loading ... !!!</h3>
}
return (
<>
<BrowserRouter>
<Routes>
<Route path="/" element={<LandingPage />} />
<Route path="/secure" element={<TestCompoent />} /> //How to secure this component
</Routes>
</BrowserRouter>
</>
)
}
TestComponent.tsx
function TestCompoent() {
return <div>Private</div>
}
export default TestCompoent
How to create a component PrivateRoute
, that checks is user is logged in, otherwise navigate to keycloak login
2
Answers
Unfortunately, you can’t completely secure something on the web interface, but you can restrict access to a private link! For example:
You can create Wrapper for private links:
and wrapper. In this wrapper you can check, is user valid, AUTHENTICATED or another checking:
App.js
Explaination:
Here
TestComponent
is PrivateRoute inside it checks if user is logged or not. You can replaceisLogged
veriable with your condition which checks the user logining. if user is not logged in it will returnLoading...
(where you can return you component where you want to navigate user when user is not logged in.)if user is alredy logged in then if will return
children
which is component.In
App.js
as you can see:your component here you can put your secure component
which is wrapped byTestComponent
[every thing you wrap withTestComponent
will be display aschildren
in TestCompoment].you just need to wrap your secure component with
TestComponent
wrapper 🙂if you still don’t understand feel free to ping me on discord [discord link is in my bio].
Hope you got your answer. if you see any mistake or have any suggestions feel free to comment here.