I have done a very big scan of answers here but I am getting more confused as I go...
So I have a React frontent + a set of middleware functions that handle among other things authentication. I have decided to use JWT tokens for this + storing them in cookie with httpOnly and secure flags.
The initial auth works and I can see the cookie returned on my browser.
What I am unsure about: How can I then apply this to the whole app and protect all the relevant routes?
Here are some parts of my app that are relevant (using react-router-dom and react-redux)
App.js
const App = () => {
return(
<Provider store={store}>
<Layout>
<Routes>
<Route exact path="/component1" element={<Auth><Component1/></Auth>} />
<Route exact path="/component2" element={<Auth><Component2/></Auth>} />
<Route exact path="/login" element={<Login />} />
<Route exact path="/" element={<Login />} />
</Routes>
</Layout>
</Provider>
);
};
Login.js (the main function of it at least)
const handleLogin = async (username, password) => {
const data = await authenticateUser(
{
username: username,
password: password
}
)
if(data.success){
dispatch(loginSuccess(true)) //simply adds a "isAuthenticated: true" in the store, but this seems useless to me
setAuthFailMessage(null)
navigate("/component1", { replace: true })
}
else {
setAuthFailMessage(data.message)
}
}
Auth.js that wraps around the private components
const Auth = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false)
useEffect(() => {
async function check() {
const checkAuthenticated = await checkAuthentication(); // reaches to the server and checks if the user has a cookie, because it can't be read locally?
checkAuthenticated.isAuthenticated ? setIsAuthenticated(true) : setIsAuthenticated(false)
}
check();
}, [])
return (
<>
{
isAuthenticated ? (
<div>
{children}
</div>
) :
(
<Navigate to="/login"/>
)
}
</>
);
};
export default Auth;
What seems wrong to me: I wouldnt think that the right approach is to call every time the checkAuthentication() endpoint, because that seems too inefficient as the user navigates from component to component it will be making tons of requests.
So basically I am looking to understand, after I get initially the httpOnly cookie, what is the best way to "apply" it to the rest of the app without making requests again every time the user changes to another route? I know nothing is needed to make subsequent API requests, but looking to see how I handle local app routing but without using insecure methods like localStorage or just checking a boolean from the store. I hope it makes sense.