Managing a JWT Session with React? - reactjs

I have a very general question concerning a JWT Session.
Whenever I fetch something from the database I need to sent the token along to autentificate. In case the token is expired, I need to check if the token is still valid. How do I manage this in a simple fashion? So that the user is directed to a login page whenever the token is invalid?
Do I always have to dispatch my intended action (e. g. a GET req. to fetch news articles) and dispatch a SECOND action everytime which deletes the token from SessionStorage if it is not valid and redirects the user to the login screen? This seems like a bad solutions because it somplicates literally every action?
So my basic question is, how do I manage a JWT session in a good way?

JWT token usually comes with the expiration time, store it in local storage and refresh it when needed.
sample code : https://auth0.com/docs/quickstart/spa/vanillajs/05-token-renewal

Related

How to design React signIn proccess with NodeJS and sessions stored in cookies?

I have React signIn form and sessions mechanism implemented in NodeJs. In React I have protected routes only for authenticated users.
How should I check if user is authenticated. I have two ideas:
If user sign in for the fisrt time I can save this information in LocalStorage and then evrytime just check localStorage.
Send request to NodeJS server every time to check if user is authenticated.
Do you have any other ideas? Which solution should I pick?
I tried both options and second one is more UI unfriendly becasue I have to run loading state evrytime I am waiting for auth response. On the other hand, first option has also disadvantege, because I am based on token in LocalStorage which can be malicious.
Every time a request is made to an endpoint that requires authentication, the request should contain proof that they are who they claim to be.
The classic way to do this is by storing some sort of "Session ID" in a cookie or localStorage (client side), that you send along with every request.
Using a "Token" (e.g: JWT) instead of a "Session ID" is another popular way to handle authentication.
Check out this article for more information about both: https://dzone.com/articles/cookies-vs-tokens-the-definitive-guide
To return to your question, I'm not sure what you're worried about in regards to a "malicious Token in localStorage" (Or do you mean localStorage can be malicious?). But for a secure application you have to either:
Store something client-side
Require your user to provide credentials (username + password) for every request

React Query to store global state for user?

Is there a way to use react-query to store global state for user, if user is logged in or not?
Right not currently I am only storing cookie as bearer token and refresh token
And I am forcing react query to hit an API endpoint that checks if user has valid bearer token
So right now its making unnecessary requests and getting failed error response if use is not logged in.
What can I do to store user info when user is logged in, so that I don't have to make unnecessary requests to /verify endpoint?
There are several options to do it. But most common are:
Keep auth data in localStorage and before API call check if the authToken is not expired.
Keep auth data in the cookie and do the same
This will help you to avoid unnecessary requests and you will be able to make requests even after page reload/closing the browser tab

Best ways to check if the user logged in or not in reactjs

Maybe it's a silly question but I'm a bit confused about this.
I want to check whether a user is logged in or not but I don't want to use localStorage to save my JWT token. I know that I can easily save it in localStorage and check from there but for my application, I'm sending the JWT token through an HTTP-only cookie from the backend and from the frontend with every request I'm sending this.
So I'm confused if it is in an HTTP-only cookie I can't retrieve this through my script then how can I check the logged-in status except for local storage.
After googling sometimes I got one answer is using the redux-persist library to persist the application state but still under the hood it's doing the same job creating a copy of my state and saving it in local again which I don't want.
Anything else I can do about it or I have to use local storage ( maybe instead of saving the token I can save the user id or some other key: value pair)

Token exchange in localstorage gets data from other users in react js

I am consuming an API in react js. I get the user's information (username, email, permissions, etc.) from his token, which is stored in localstorage. However, when replacing it with another valid token from another user, I get their data. I think it is a serious security problem. Is there a way to solve it?
For now it occurs to me to compare the value of localstorage with a state with the token. I consider that it is not the best because it will have to be necessary in each request to the backend. Or request your password to make changes. Also refresh the token.
This problem is exposed when wanting, for example, to edit the user profile.

best way to keep user logged in using JWT and axios

how to keep the user always logged in, in a react application.
I can't refresh the token using an expired token, can I ?
my idea is to make the token expiration to null and refresh it in every request for security
so if user don't use the app for a while, token will never expires, and in every request the token will be refreshed for the security
it's not secure to do this. because now the token will still valid as long as no new requests from the user. tokens that never expire extend the time-frame for attacks such as cross-site request forgery (CSRF), session hijacking and session fixation. also if you want to change this behavior you will need to change it from backend side not react.js side
I might be misreading your question, but at least just on "how to keep user logged in"
You can do this with localStorage, ofcourse there is security concern.
Basic idea: user logins, the user object returns from database, you only need to store the jwt_encoded information that makes a user "looks like is logged in" in the localStorage. By that I mean, you aren't going to return the user's password & email everytime, and on refresh page, log the user in with those credentials... If you are building a todolist app, just store the todolist tasks & username to the localStorage after the user logs in for the first time. And then if the user refreshes the page, just display the information from the localStorage.
It might be a little bit more tricky because UI is dynamic and you have to change your localStorage to change your UI, but on backend calls that update our user object, we can simply return the new user object and set that as the new user in localStorage.
Best to check this article for code, https://blog.bitsrc.io/build-a-login-auth-app-with-the-mern-stack-part-3-react-components-88190f8db718. The author starts talking it about half way through. I only provided theoretical stuff.
Edit: I really was falling asleep. For the "it might be a little bit tricky part" I was being quite dumb. If you saved the user id in the localstorage, you can just make api calls to retrieve the user information with that id whenever you need it, in short, you only need to store user id in localStorage.

Resources