How to safely store and access user session data - javascript

I am currently learning about security aspects in web applications.
My application used to identify the current user by a cookie which was created on successful login. It contained the user's id. Every time the user has made a request to the database, my application would use that id to select only those results that were associated with this id.
However, as I learned, it would be no problem at all to simply change that cookie's value and therefore get access to another user's data.
My issue now is: how would I safely store such data and make it available to both PHP and Javascript?
I thought of HTML5 sessionStorage, but that would be vulnerable too.
My second thought was to store it by PHP only in a $_SESSION variable, but then I could not access its value via Javascript.
I feel like I can not wrap my head around the basic concepts of how to create a secure and functional user-management system.
Any help will be appreciated.

I would store the user id data only in the session. Why do you need cookies?
To communicate between JS and PHP use ajax. Best library for this is jQuery
.

Simple solution:
Add a userKey field to the database.
When user logs in, generate a random unique string and save it in DB
Save this string in cookie. Save user ID in cookie.
On the next visit, select from the database user with the corresponding userKey and ID.
It is somewhat secure, because the string is random, so only bruteforce helps.
Longer the string - harder to bruteforce.
The solution is simple, it can be upgraded by using crypting of ID, checking IP, etc.

Related

Understanding Local Storage & Cookies in Javascript

I have a form on my page with text boxes, radio buttons and drop down menus that ask questions about students. The options selected from these will later be used to make a div containing each student's content. My directions say to save the list to local storage. I'm confused on what exactly this means. I tried looking this up and cookies kept coming up. I thought these were 2 different things. I'm confused on the concept of local storage. I've searched this on Google and Stack and have read what ever I could find related to these topics. I think I need this explained in a simple way rather then reading a textbook definition or answers to questions people have asked about there code relating to cookies and local storage. Can someone explain these 2 topics? Are cookies and local storage the same things? I'm not sure if it's different for other languages but I'm using Javascript.
localStorage is an API that the browser provides to allow you to read and write data. You can kind of imagine it as a single large JavaScript object, storing data values under different keys. Using it is easy: localStorage.setItem(key, value) (for some key and value, e.g. localStorage.setItem('test', 23)) to write a value and localStorage.getItem(key) to read/access that value. Details and examples can be found here
Cookies are accessed through the API document.cookie. document.cookie also uses pairs of keys and values (the cookies) to store data; however, the approach for reading and writing cookies is different. To create a new cookie, you enter document.cookie = "key=value" (for some key and value, e.g. document.cookie = "test=23"). To see all cookies, enter document.cookie, which will spit out all cookies as a string of keys and values, separated by semicolons (e.g. "test=23; someOtherKey=59"). Unfortunately, this makes reading cookie values a little trickier than with localStorage; the simplest way to get the value for a single key would be to use a Regular Expression, a specific pattern for matching text. More details and examples can be found here.
In terms of how you use them, they're similar in that they both are used for storing data. However, cookies are mainly sent to the browser from the server along with the page; localStorage, in contrast, is only accessible to the JavaScript code in the browser.
Hope this helps!
[EDIT]
See also
Cookies and localstorage are not the same things.
Cookies
Cookies are small files that contain information useful to a web site — such as password, preferences, browser, IP Address, date and time of visit, etc. Every time the user loads the website, the browser sends the cookie back to the server to notify the website of the user’s previous activity. Cookies have a certain life span defined by their creators and it expires after the fixed time span.
localStorage
The localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions. That means it won't clear until you remove it. In another way, localStorage has no expiration time.
Add data to localStorage
localStorage.setItem('myCat', 'Tom');
Remove Item
localStorage.removeItem('myCat');
Remove all items
localStorage.clear();
Also, there is another thing called sessionStorage. Which is same as localStorage but data only stored until the browser session is closed.

Is it possible to keep variable values after page reloaded in JavaScript without using cookie and local storage?

I am trying to keep values for a page over user interaction. I know I can do it using cookie and local storage. But I am curious to know that is there any way to do it without using cookie and local storage. If it is possible then how?
Actually I am asking to do it without any storage.
Update url for each action made by user so you can retain the parameters you want on page reload, I don't think we have any other way
IndexedDB is another option for client-side storage. Its API is a bit complex though, so to use it, you might want a library like localForage instead.
Another option is to save the values by saving them in a database on the server, though for reliable retrieval without storing any information client-side, the user will have to be able to input something unique to them (such as username/password - the server checking their IP addresses likely won't be enough, since IP addresses are often shared)

Does each user only have 1 session id?

I'm still a beginner in using sessions and cookies and I don't understand this, so I want to ask:
1. Does each user only have 1 Session ID?
2. What is a Session ID?
I tried to store data in session, but when I tried to store other data it had a same Session ID. So how do I know who this data belongs to?
I actually want to make a shopping cart in react.js SPA using backend express. but i dont know how to store this data cart. so far what I have done I want to save the data cart into a session, like product_id and product_variantand then call this product_id and product_variant in database based on this Session ID.
Correct Me If I'm Wrong. Thanks
You should be generating the session ID & then storing it in a database & attaching it to a user ID. That way you know the user by looking for their session ID when they move around the website/software.
You can also record things like their IP address, browser information, and time of access to make it a tad bit more secure - making it harder for a hacker to hijack their session information.
Also, the only other thing I should mention is that you should not be storing private information in the session data. For example, do not store their account ID in the session variables or their password/email/username/etc. It is possible to modify session data & access other accounts if you rely on the session data itself to tell you who a user is. The encrypted/randomized session IDs can be so unique that it is near impossible for a user to reasonably trick your server into thinking they are a different account. So that's why we store them in the database w/ additional information instead of setting other session variables.
Example:
In PHP we could have the session_id(), but also store things like $_SESSION['setting'], or $_SESSION['theme_choice'] and other trivial settings to prevent having to look it up in the database every page load.

Save Form Data for when user returns

Here is my problem...
We have a very large Form with many inputs and check-boxes, the problem happen when the user's pc disconnects he then need to restart the form.
After doing many Google searches I've found a few solution but i have no exp using any of the following and would like to know which solution is better used.
Save a session with post variables so that when user returns his data would be saved. (problem is with session destroyed when browser leaves page.)
Save the post variable to a temporary table, and if host name of user is there to populate the form to continue where he left off. (Probably the simplest way)
Session Storage and Local Storage, Both of these seemed like a good alternative but haven't seen any examples or any docs on how this can be used to populate forms.(No Exp with this.)
I'm thinking of using the second option and just wiping that table after 1 hour but would like to know which is better in terms of what is more widely used for this solution.
Thanks
you can send the data with the onBlur on the textfields with ajax post to a php file which writes them into the session or a coockie or a database.
Session ends when the Browser(not the tab) has been closed. Coockie must be aktivated by the user. So i think the temporary table is the best solution for you.

Content Rating Widget using XSLT

I have created some solution for content rating in our websites using XSLT. User is allowed to rate whether he likes the article or not. by clicking yes or no. I want to somehow avoid the user giving multiple feedbacks for the same article. I thought of handling it in Database by using sessionid and ip address but that would create unnecessary space in DB. I want to filter the request before its been sent to DB itself.
I don't think you can avoid DB if you are aiming a perfect solution. You could use for example cookies or any kind of session variables to store the necessarry information, but that's not enough: user can delete cookies or log into your application from multiple computers. If you want to prepare for every situation like this you need the information retain over sessions: DB is the solution.

Categories