Trouble with session-cookie authentication
Hi,
I'm trying to get authentication working and I'm not sure I'm going about this right.
My backend uses JSESSIONID cookies. So POSTing a user/password to an
I have also added a global axios response interceptor which checks for
My problem is that when I first try to access a protected route without having the JSESSIONID cookie, this all works BUT I get the following warning in the console:
/auth/login endpoint yields a 200 OK and sets the cookie. From then on withCredentials: true on axios ensures that the subsequent requests don't yield 401s (I'm skipping over CSRF etc as that's not a issue here).I have also added a global axios response interceptor which checks for
401s and navigates to /login (I had to wrap my axios instance in a context into order to access useNavigate). This will catch session timeouts and send the user back to the login page.
I'm protecting 'authenticated' routes with a route guard that uses a useUser hook. This hook calls a /users/current endpoint which either yields the current user's info or a 401, thus redirecting to /login.My problem is that when I first try to access a protected route without having the JSESSIONID cookie, this all works BUT I get the following warning in the console:
You should call navigate() in a React.useEffect(), not when your component is first rendered.
This suggests to me that something about my approach is off but I'm not quite sure how to work around this.
The code is here (stripped to the bare minimum) : https://github.com/ChambreNoire/auth-test
CheersGitHub
GitHub - ChambreNoire/auth-test
Contribute to ChambreNoire/auth-test development by creating an account on GitHub.
2 Replies
exotic-emerald•3y ago
Hi 👋
I imagine this is happening as you're calling navigate from the interceptor. Try replacing the URL using the Window API and not the React Router API and see if the error disappears.
vicious-goldOP•3y ago
That is indeed what is happening. I fixed it by making the
/user/current endpoint return a 200 OK with a null payload when the user isn't authenticated so that the interceptor isn't called during a page refresh. Then the useUser just handles user !== undefined for routing (although I'm not keen on this) .
I'll give the window API approach a go.
Thanks!