Reputation: 61
I just started working on a simple website using Reactjs where you have to login to view certain pages. This is my first project using Reactjs and thus I do not feel as confident in react in comparison to more traditional approaches such as PHP-based websites and security measures.
Recently I was researching how to create pages in Reactjs that are only accessible when you are logged in. And I found this approach where the basic idea is the following:
if(isAuthorized()){
// show protected route
} else {
// redirect to landing page
}
where isAuthorized()
could be just a state
(as presented in the post) or (as I would probably do it) a function which always asks the server "Hey, am I still logged in?" and to use the response to ether show the page or redirect to the landing page.
But now comes my question: In a standard PHP-approach you would have to ask the server for permission each time you want to access a website and the sever can simply refuse to respond with the protected website potentially containing top secret information. But when you use the proposed code, the check isAuthorized()
runs on the users machine, right? And thus, all the information (login page, landing page AND the protected pages) must already be in the users memory somewhere, right? So to check whether the user is logged in or not doesn't matter for attackers as they get all the information as soon as they load the login page. And even if that would be save, the attacker would just change the return value of isAuthorized()
because all the code is running on their machine.
It might be that I am still not understanding the basic mechanisms of Reactjs and maybe all my thoughts are nonsense. If this is the case, I'd love to get a better understanding of Reactjs. If I did understand everything correctly than maybe there is a more secure approach to achieve a simple login system in Reactjs
Upvotes: 3
Views: 1338
Reputation: 586
If you store an accessToken in the localStorage you could post the access token to the server and verify it, and then use the approach you showed. But something like this:
const verify = (accessToken) => {
axios.post('verfiyurl', accessToken).then((res)=>{
return res.verfied // res.verfied is true or false
})
}
if(verify(accessToken)){
return null
}
However as long as you have authenticating on the backend, which you should. The approach you posted is more than enough.
Upvotes: 1