Persisting User Sessions with Httponly Cookies in React - reactjs

I'm trying to figure out what the best way is to fetch user data / persist user sessions on the client side via React, when using HttpOnly cookies to store session data.
I was thinking of doing something like:
useEffect( () => {
const getSession = async () => {
const session = await fetch('/session/current')
if(session){
.... there is an active session
.... set the local state to hold user data
}
}
getsession();
}
So the issue I'm trying to figure out is, when the user logs in and closes the browser, then re-enters my website. How do I validate that the user still has a valid session, and then send necessary user data to the client side to know that the user is authenticated?
When the user logs in and cloes the browser, there is still a valid session HttpOnly cookie on the server side. Is the best way to just hit an endpoint, see if there is a valid session, then return user data?

There is no way to handle this from client side as it is an httponly cookie. You need to send the cookie to the backend to validate session. If users close and reopen their browser, they loose their cookies. In order to keep them logged in you will need to track some other information from the user like their IP address, OS, browser type, etc and save it in like memory cache for a ttl. But it is not secure to do it that way.

First of all, once your get the cookie or token from the server after user logs in, you will have to store in it local session storage in browser itself, so if user closes the browser and reopens it would have automatically logged out,
Or do mention ttl, so that it will have some expiry time as well

Related

storing username and email in a session

I am using nodejs backend where I send a httponly cookie (xss protected via nodejs backend) with a jwt token.
And this question is on front end. I need to get logged in user. my front end is react.
Tutorial I followed used res.local = currentUser in a isLoggedIn middleware. so for every request currentUser is sent if logged in.
I was thinking , 1. I found out I can't access res.local from react.
2. So then instead of that I can send my response object with isloggedin:true and logindata:currentUser. Now if I do this. For every request this middleware runs and attach currentUser object. Is this a safe thing to do?.
3. Or can I save username and email on a session when user log in, and let middleware to only send isloggedIn true or false in response. then I can read session and use user details if isloggedin is true.
I need to know out of these two what is the best practise.and safe to use. If I let user comes in every request(but this includes just any page even when I retrieve product details, current user will tag along in the request) it is easy. else I will have to read sessions as well. (xss protected via nodejs backend)

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

ReactJs How to check user authenticated and sessionID generated by ExpressJs

I have a Nodejs application creating a session when the user gets authenticated.
I see that Expressjs stores the sessionID in a cookie which at the moment is HttpOnly and the session info itself is stored server side.
How to check that the user is authenticated and there is an open session from ReactJS (that is, browser side)?
I think that the only way is to try and access that sessionID? What is a good way of implementing this?
Thanks.
The register or login should respond with the necessary user information to the client side on React so that user information could be stored in the application state (Redux/Flux). The sessionId stored as HttpOnly cookie by express server is solely for the purpose of Express to uniquely distinguish a browser session.
Ideally you would need another API as well to return the user information which at the Express server side should read the sessionId cookie and return with the currentUser information back to the client. Suppose, you login and the user information is stored in the UI application state, and when you refresh the browser, this application state would get flushed off. In such a scenario, this API would help to restore the application state with the current logged in user information. Hope this helps.

AngularJS: is this a bad practice for authentification?

I'm new in AngularJS. I use Drupal as Backend for APIs.
So this is my problem:
When the user is logged-in, Drupal saves automatically the SessionNAME = SessionID in the cookie to keep the user logged-in so on refresh the user is still logged-in but i loose the userId, the username, his email, his favorite movies...
My solution was: sending a request to the server in app.run() to get logged user data and I store these data in AuthetificationService.currentUser so if a user is logged i will have all his data otherwise currentUser will be NULL.
Is that a bad practise?
NOTE: Please if your suggestion will be webStorage or cookieStorage tell me exactly what i need to store and when i need to empty the cookie or the local-storage.
Here's the practice I follow and is usually used:
Login->
create session on server ->
store the user object and important info in localstorage
e.g.
localStorage.setObject("myApp_user",user);
localStorage.setObject("myApp_movies",movies);
Refresh Page (check session)
check session(if logged in) ->
get the user data from localStorage and use it
e.g
UserService.user = localStorage.getObject("myApp_user");
MoviesService.movies = localStorage.getObject("myApp_movies");
Logout
close session call on server->remove cookies->remove data from localStorage.. e.g.
localStorage.removeItem("myApp_user");
localStorage.removeItem("myApp_movies");
Hope this helps.

Can I use html5 local storage for storing user authentication session information

QUICK BACKGROUND:
I'm writing a Mongo/Express/Angular/Node SPA and using passport I have setup OAuth log in options to handle the user authentication / authorization.
With passport I am successfully maintaining session on the server, so all my XHR requests (that need it) are checking for a logged in user.
On log in the server puts the basic user session info into a cookie for the client to find on the authorization callback, I then am using angular-cookies' $CookieStore to access that cookie on the client save it to the rootscope and clear the cookie.
PROBLEM:
This is working perfectly except for any event where the user refreshes the browser, which causes my rootscope session to obviously get wiped.
So I was considering storing session information in the browser local storage (using store.js) then even on the initial load I could check for the session existing in the browser local storage and bypass the OAuth login if there was already a session.
Is it bad practice or is there some logistical/security problems with storing user session information in the browser local storage?
This app doesn't have any senstive data, sign up is free and logging in is really only there so I can track users and store data created in the application for each user. And the user session would never have a password (I only allow OAuth login no local option).
Instead of the localStorage, look at sessionStorage object: http://www.w3schools.com/html/html5_webstorage.asp
It works exactly like localStorage, but the whole sessionStorage object will be deleted when the browser window is closed - but will survive any page refreshes. It is an ideal place for storing session ids and alike.
But be warned that the sessionStorage is isolated within a browser tab - that means if your user choses to open a link in a new tab, the sessionStorage for that will be initialized empty.

Resources