I want to store user-clicked data in a cookie which never has to go to the server. Its like a session-added data, which I want to persist over sessions, as in the data just keeps adding to the cookie, and it is stored for a long time, and only gets deleted when the user removes browsing history. The cookie is pure-client only cookie and it never has to go the server, as I don't need the user generated data at the server, so I want to get rid of the additional overhead the cookie creates in sending back and forth between browser and server. Is it possible to achieve this?
I know it´s a little late for you, but this answer is for all who have the same problem.
With HTML5 you can use web storage.
(Just an idea! - not tested!)
You could define a cookie (via javascript on client) and set the "secure"-attribute.
In this case, the cookie will only be sent to the server on HTTPS connections.
To make sure the cookie never leaves the browser, you just never open a HTTPS connection ;-)
EDIT
Now it´s 2022 and I would not recommend solution 2) anymore.
Instead of setting the secure flag on the cookie, set the path to a path on the server which is never used.
If browser compatibility is a concern you can use a some javascript to wrap around various different technologies. Older versions of IE support (supprise supprise) a proprietary version of localstorage called userData (I don't think it's exactly the same, but should do what you need).
A wrapper script like https://github.com/andris9/jStorage or https://github.com/marcuswestin/store.js should do what you need it to do.
I'm 100% sure that there is no way to force cookies to be client-side only, they are allways sent to server. There is however possible to do the opposite: server-side only cookies (not readable by javascript) by setting HttpOnly flag on cookie.
Use an impossible path to set the cookie:
document.cookie = "cookieName=...; expires=... ; path=/never_reached/ablkappmqlnahsuia";
Related
I am currently working on an application (React frontend, node.js server and api) and am using JWT. I am having a hard time wrapping my head around the process of storing and sending the token using HTTP "Authorization" header.
Tutorials online seem to do a great job of showing me how to send this token once it is stored somewhere, but how does it actually get stored there in the first place is where my confusion arises.
I have two ways of thinking of approaching this:
The token is generated on login, then returned to the frontend, then stored in localstorage. Then, when a request is made, the HTTP "Authorization" header is set by pulling the token from local storage.
The token is generated on login, then returned to the frontend. It is somehow stored already in the "Authorization" HTTP header (Does this even make sense?). Then when a request is made, the header is already set.
Do option 1 but use a cookie (or session-cookie?) (don't know how to do this approach).
I would like to know:
A. Which of the 3 (if any) is the right approach
B. If approach 2 is the correct way, how do you actually STORE this header once you get the token?
C. If NOT approach 2, where is the preferred place to store this token (localstorage, cookie, etc.)?
I have tried approach 1, it works but seems unsafe and not best practice.
I have NOT tried approach 2, because I have no idea how to do it, and couldn't find anything online.
I have NOT tried approach 3, but I assume it could work in a similar fashion to 1?
First, your instincts are right; you should not use local storage for a secure token because local storage persists even when the browser is completely closed.
The most straightforward way to store your token is to just keep it in memory. A global variable in Javascript, or even attaching it to window, works fine. Then with every XHR call you insert Bearer [Token] into the Authorization header yourself. There are a bajillion npm packages to help with XHR requests but virtually all of them should let you insert this header. If you haven't already you should write a single wrapper function to encapsulate all your API calls and insert the token at this point.
The drawback with this is that the token won't persist across different pages on the same domain or across browser tabs, nor will it work with non-XHR requests like img src="https://secure_api_route_that_returns_an_image.jpg", as there's no way to programmatically inject custom headers in those cases. I don't know if any of that is a problem for you. Usually with React SPAs you aren't going to be bouncing around truly different "pages" on the same domain, but you may well want to be securely sourcing images with what are technically API routes, or keeping the session alive across browser tabs; I'm not sure what your requirements are.
Anyway if you do need any of that functionality, you have to use a "session cookie". (Technically you could use session storage if you only need to preserve the token across page navigation but it doesn't work across tabs, so I find it to be pretty useless over just storing in-memory). This just means a cookie with no expiration date, which is automatically purged when all browser tabs have been closed. You must enforce earlier expiration on the backend rather than through the cookie header.
I use .NET backends rather than Node, so I can't give you specific code, but basically you need to return this header in a successful login API response:
set-cookie: myCookie={jwt}; Path=/; Secure; HttpOnly; SameSite=Strict;
Don't omit Secure, HttpOnly or SameSite=Strict except possibly in development, as otherwise you'll be open to common vulnerabilities. (This is one of the disadvantages of the cookie approach; it's easier to implement wrongly and open up a vulnerability). This assumes your frontend and backend are hosted on the same domain. It becomes a little more complicated if not (CORS, etc.) but it can be done in that case too with a little more work.
On the authentication side, you will just need to look for this cookie in every API other than login. If everything is working right the browser will automatically send something like this with every request to your domain, on any tab, for as long as any browser tab remains open:
cookie: myCookie={jwt}
Again not a Node.js guy but I'm reasonably sure most any library that can verify a token via the Authorization header will support cookie authentication too; you'll need to check the documentation or please post a new question if you can't figure it out.
On the frontend side, besides the cross-tab support, the browser takes care of saving the cookie and sending it when it should, so it's conceptually close to what you're looking for in option 2.
So as with most things there's no single right way (though there is definitely one wrong way - localstorage). For what it's worth, a few years ago I surveyed several commercial sites to see how they handled this, and I found most used the session cookie. This included U.S. banks and financial institutions, which have to follow some of the strictest security standards that exist. While cookies sometimes get a bad rap, when used correctly they are still industry standard for secure authentication. But storing the token in plain old Javascript memory is fine if you don't want to deal with cookies or need the features cookies give you.
I am setting http-only cookie from the server for storing some user info so that i can validate user on backend. Say some hacker steals this cookie from someone's browser and go to my webpage and add the same cookie using document.cookie = "cookie_name = cookie_value" if cookie is not there. If cookie is there then he can delete the existing http-only cookie using chrome developer tool and later add it using document.cookie = "cookie_name = cookie_value" on his browser.
Now when server gets a call from hacker browser, it gets a cookie set by hacker and would validate it. How can i stop this?
Cookies leave you vulnerable to Cross-Site Request Forgeries and their kin. Not just hackers stealing cookies, but hackers borrowing a user's browser which already has the cookies. This is part of why tokens are more common today.
If you have to use cookies, there are various things you can do to make them slightly less insecure--updating the cookie on each request, verifying request IP against sending IP, configuring your web pages not to allow the loading off offsite content, forcing re-login for any major actions, and other user verification means. None of them is perfect.
Simple: You cannot. http-only serves a different purpose than validation. Your assumption that a hacker will use a browser is the first problem you have. I would never use a browser for something like that since a browser would restrict me. I would forge a HTTP request with my own tools and send a header with http-only and secure and whatever you want me to to your server.
If you want to validate your cookies, you will need to implement your own solution instead of relying on browser mechanisms. You could for example bind the cookie to a certain IP range and add some kind of token to the end of the cookie-key or cookie-value.
In general, do what #bryanx says. DO NOT USE COOKIES TO STORE DATA. They are fine for session tokens and the like.
Don't use cookies.
Cookies are necessary for preserving information between sessions, but any time you leave information on the client, you open yourself up to potential issues like you described. If you only need the information maintained during the user's session, you may want to consider using a $_SESSION instead of a cookie.
If you must use cookies, you may want to consider building out logic that if the cookie doesn't match a previously authenticated device, that you challenge the user again for their credentials. There are many ways to solve for this, just get creative.
Im developing a web application which requires cookie to be set httpOnly = false.
Since, I find no other way to pass authentication cookies(for checking whether user has logged in successfully) from server side to be accessible via Javascript in my front end. This cookie is then used to send an AJAX request to my server side(added to the header). (Please do correct me if Im wrong and suggest me any other way)
My question:
How insecure is httpOnly = false? Is it safe enough with just forcing it to use cookieSecureOption = true so that it will always be send via HTTPS.
How can I protect it from XSS attack?
A "non-HttpOnly cookie" isn't a vulnerability in itself.
An "HttpOnly cookie" mitigates the risk of an XSS attack. That is, any attacker injected scripts into your website will not be able to grab the value of this cookie, thus protecting the session.
If your application requires the use of the cookie value to add as a header, then you cannot mark this cookie as "HttpOnly". You can change the request handler to look for the value in the cookie rather than in the header (so you can set the flag), however this may put your site at risk of CSRF. The most secure approach is for your handler to check authorisation via a "HttpOnly" cookie, and to use another token value in a header ("non-HttpOnly") to check for CSRF. If these values are different, e.g. in the encrypted token pattern or the synchronizer token pattern, then there isn't much value in attacker in only retrieving the one value via XSS because they can't use it to authorise requests. Note that any XSS vulnerability is usually a bigger problem than a CSRF vulnerability, because the attacker could always use their XSS attack in order to submit requests directly from your site, however it is a much harder attack to accomplish. At least with "HttpOnly" they cannot grab the auth cookies from your site in order to remotely login.
The other cookie flag you mentioned is the secure flag. This will limit the cookie scope to https connections only, and is recommended if you are using https (which is also recommended). This does not affect whether JavaScript can access the value though.
If you do use a "non-HttpOnly cookie" then you can still mitigate the threat of XSS as follows.
Move all script code into external js files and set a Content Security Policy to prevent any inline scripts from executing.
Make sure you are correctly encoding all user input when output (e.g. < becomes < in HTML) and run a web security scanner against your application.
If you do not have HTTPOnly flagged, your users are still more vulnerable to XSS than they otherwise would be, as the cookie can still be accessed from JavaScript. From your description, you should not need access to the variable from JavaScript, simply access the cookie from the server side (which is still possible with HTTPOnly flagged, cookies are sent with every request including AJAX calls) to retrieve authentication information. The Secure flag and HTTPOnly flag defend against completely different attacks.
There is a hybrid way of doing this. I say hybrid because it involves half of what your doing and a mix of what bksi mentioned in a comment.
Since I do not know your full scenario this answer assumes you are just looking for a way to authenticate the user before allowing them to make changes or start a process server side; login, viewing an account page, and so on. You should never rely solely on httpOnly = false I would recommend using it with what is below.
A Solid Solution
Set a normal cookie when a user logs in successfully, this does not need to be sent over HTTPS although it would be nice. This cookie should be a randomly generated token for their session. I usually hash (md5 encrypt in PHP) their user id (assuming you use a database) and a time stamp of when they logged in. This insures the token is unique.
Now that you have a token saved on their local machine as a cookie also make sure to save this token in a PHP session which is server side. Now any time they visit a page or an AJAX request is sent you can compare the local cookie to the PHP session value server side. This is the fastest way you can authenticate a user interacting with your server. If the values match they are legitimate.
Now this is not entirely secure. The local cookie can always be edited which is something we usually don't care to much about because this will only harm the user by invalidating their session. On the flip side a crafty hacker could alter the PHP sessions and that could invalidate other users because their session was erased or hijacked. A hacker would have to get a legitimate session token and make a cookie to match.
The Better Solution(s)
1) On the server side you could use a database instead of PHP sessions. The process remains the same but now you need to do a bit more work of keeping the sessions table in your database up to date. Usually this is done by saving the token with a time stamp and updating this time stamp every time the token is checked. If the token is checked and the last time stamp is really old (you decide how long that is) you can un-authenticate the user by destroying their local cookie and having them sign in again. This is more resource intensive though and can slow down sites with large traffic loads.
2) Use a form of double authentication. This would be using PHP session 90% of the time for simple things but when an extremely important process comes up, say updating personal information or providing credit card information, check with the database as well. This would require two different cookies to be saved on the users machine. One if for checking PHP session for authentication and the second is for checking the database. This scenario would be really hard for a hacker to break through to the more important things because they would need to figure out both tokens and the database one is not easy to steal.
Final Thoughts
This is a fairly secure answer but you should still implement extra security precautions. It seems you are misunderstanding how cookies work in general; your recent comment sounds like your using cookies and ajax backwards but maybe I'm misunderstanding. Here is how I do it:
[User]-> Tries logging in to website with a login form
[Server]-> Checks this information against the database Pass, log 'em in.
[Server]-> Generate and set a random token as a cookie
I use PHP here and usually store this cookie with a name like sessionToken. This cookie immediately exists now on the users computer and we, the server, always have access to it server side; we can call it up any time. This is not really secure though because people could copy the cookie without the person knowing/ steal it as we send it to them. I'll deal with that in a minute.
[Server]-> Create a PHP session (session id: abc123) server side that has this same token.
This is step one in security. PHP sessions are not as easy to steal or hack. So even if someone steals our users token cookie when they try to use it on their computer it will fail. Here is a vaild user:
[User]-> (PHP session id: abc123) Tries to access secured page or content. PHP session is called up and is checked against the cookie token. If they equal each other this attempt passes.
Here the user has a session on the server they don't know about that recognizes who they are and can be accessed only by the server; usually. It is here where your AJAX request come into play. Every time the user tries to do something that you want to see if they are even allowed to do, send a request via AJAX to a PHP script that authenticates the user. All it does is send back PASS or FAIL. Then you can use AJAX or Javascript to do whatever you need. Here is a hacker exmaple:
[Hacker]-> Steals a cookie from a user over a cafe's wifi.
[Hacker]-> Tries to access the website you are on with it.
[Server]-> (PHP session id: ???) Doesn't have one, destroy the cookie and ask this user (the hacker) to login again.
This is as much information and help I can give. Your latest comments are starting to sound like new questions you should post on Stackoverflow.
I'm preparing some diagnostic tool. It operates on the website in the iframe - only by javascript.
Now what I need is to get rid of session cookie in the website that I have in my iframe. I just need to be logged out after performing some operations.
Unfortunately I cannot just drop the session cookie from javascript because it's mark with httpOnly flag. I did not found any way to open iframe in incognito mode either.
Now the rules for achiving this are following:
I can add any file to target website server
I can run any javascript on website domain
I can force user to use specified browser (it does not have to be cross-browser solution)
I can NOT modify website code
The solution have to be server and programming language independent
Any ideas for the workaround?
You just cant manage httpOnly cookies from javascript.
But I think that you want to analyze the page, but also with js. So why use iframe ?
You can fetch content of page that is to be analyzed from outside of html or javascript:
do ajax request to your application proxy
use html5 websockets as proxy server. I assume that websocket server is your. Websockets have also cross-domain ability.
You then just need to parse fetched DOM (i saw something builtin for this). And let analyzing to begin.
As far as I understand -
Given that - You will have a website with user login/logout implemented in it.
So if you can have some way for your diagnostic app to have the logout url of target website as a config var or some setting (by putting some js or file in the server) then this job can be very simple. Just let your diagnostic app load that logout url when needed.
If you simply want to prevent cookies being used in the iframe you could try using the sandbox attribute.
Seems like a very similar question to:
Disable Cookies Inside A Frame/Iframe
Hope I am understanding your question correctly.
You have JavaScript so just AJAX request to your server and tell it to unset the session variable.
Say IFrame references url: example.com/iframe.html.
Have it refer to cookieless.example.com/iframe.html instead and have a serverside reverse proxy rule setup that picks up that request and points it back to example.com/iframe.html.
Depending on how you set cookies serverside (i.e: '.example.com') cookies will only be set on www and root-domain
I think you will need some kind of server side proxy that records the cookie header value, and then resets this header value at a later stage based on a value in the request.
This shouldn't be too hard to write in any language, on IIS / .net framework for instance it would be an implementation of an IHttpModule.
The Only way is to Disable Cookies
I'm storing some preference data in cookies. However, I just noticed that this data gets sent to the server with every request. Is there a way to prevent that from happening?
A friend tipped off web storage, but this still leaves IE6/7 without a solution.
You can set cookies to be HTTP Only (so supporting browsers won't let JS access them), but not the other way around.
Web storage is the ideal solution, but you'll need to fallback to cookies for legacy browsers.
You can reduce the number of requests that include the cookies by moving some content (images, css and stylesheets in particular) to a different hostname, and limit the cookies to your primary host name.
The appropriate solution is to not store a huge amount of data in a cookie in the first place. Store it on your server, and only store a reference to the information (like a row identifier from a database) in the cookie.
Nope, no way to change it. Cookie data gets sent back with every single request to the same server, including requests for static stuff like images, stylesheets and javascript.
If you want to speed up the site and minimize server bandwidth, use a different domain name - or better yet, a CDN like Rackspace Cloudfiles - for your static stuff. The cookies won't get sent to the different domain.
Good luck!