Users can set cookies in console? - javascript

I'm wondering the best way to implement cookies to my site. I would like a user to be able to edit a given post based off a cookie that I set at the time the post is created.
I'm using Angular to set the cookie. ie:
var favoriteCookie = $cookies.myFavorite;
$cookies.myFavorite = 'oatmeal';
(per the Angular tutorial for $cookies).
My question is more at the core of how to use cookies. Wouldn't it be easy for a user to set the cookie using the console? ie:
document.cookie = 'key=value';
And get access to a post for editing? Perhaps I should be creating a unique id to use as a cookie that I then check for when the actual creator visits the page? If so, how might I go about this to best ensure only the actual creator of the post has access to editing?

You can restrict JavaScript manipulation by setting the HttpOnly flag in the cookie on a response. The console won't be able to set it programatically.

Related

Security of Cookies

Just a question about setting cookies.
Say your web application is getting information about a users location and seeing if they are in x area. If they are then we can show them y content, or else don't show them.
If you wanted to store that information in a cookie so that later the server/application will read the cookie and have certain assets/web components be showed to the user, could the user theoretically set that cookie to set themselves as a valid user in the region, thus being able to see content they shouldn't? If they saw the setup of the cookie that had been set (i.e. cookie key = userInValidRegion, val = true/yes/something), could they follow the same format and set it themselves?
Thanks

Get or Pass Sensitive Data via AJAX in PHP

I want to update a row of data in a database using Ajax and PHP; however, I'm struggling with the following issue: the field in the database to update (henceforth the id) is dependent on the page the ajax request is sent from.
I need to get this id to my PHP script that Ajax calls, however:
I don't want to set the id in a data attribute or hidden input on the page because these can both be manipulated by a malicious user.
Similarly, identifying the id using the referring URL is also prone to spoofing as $_SERVER isn't secure.
I can't set the id in a SESSION variable (or COOKIES) because the user could have multiple pages open and the SESSION would only hold the last page id that was opened.
The only solution I can think is to create a map of random tokens to id's in a table in the db and pass that in a SESSION variable (as per #3 above), then check the table for the token and grab the respective id that way. Seems somewhat convoluted though.
Are there any other options or thoughts? Thanks.
This is a problem related to OWASP Top10 A7 (Missing Function Level Access Control).
There might be no issue with putting your ID on the page so the page can send it back - you just need to validate that the actual save request is permitted for the user.
Just think, regardless of whether you put the ID on the page or not, the page does know the base url for performing the action, so they could go ahead and guess IDs anyway.
Simplify your logic. Pass some sort of indicator of what type of id is in use from the client to the server.
If you create overly complex application logic to address a security concern you will probably have more problems with your code than improvements in security.
Use SSL/HTTPS and a WAF (web application firewall - like mod_security).

When to create cookies at client side(browser)

I understand the importance of creating cookies at server side , it is for transferring information between server and browser ,since HTTP is stateless protocol.
But I am not aware about why and when cookies are created at client side (browser).
Hope my question makes sense.
But I am not aware about why and when cookies are created at client
side (browser).
Because if you want to save for example settings for the user you can use cookies. It might be easier as setting them in php $_COOKIE (serverside).
BUT make sure it is no data which contains password or similiar - cookies can be shown in the browser
document.cookie = "name=value";
document.cookie = "username=smith"; // setting two cookies
document.cookie = "lastlogin=Dec 1 2045";
...
alert(document.cookie); "username=smith; lastlogin=Dec 1 2045"
JS has a global document.cookie field (which is a magical string with
odd behavior) when you assign into document.cookie, it actually
appends / concatenates a new cookie (an unfortunate syntax that does
not match the expected semantics of the = operator)
This can be for many reasons. I use cookies on the client side to store non-sensitive information about the user that may be useful to know the next time they access the site.
For example if I am building a shopping website. I could ask the user to pick a currency and store that in a cookie so next time the user accesses the website I can read that cookie and set the currency without prompting the user.
Often, client-side cookies is used to store key to extract stored information from database or other storage
http://screencast.com/t/mzvp9jTP

Adding a class to Body in PHP and keeping it with a session

I've been trying to figure this out on my own, but I can't seem to get it sorted.
I'm building an accessibility section on a client site, and i've got two buttons, the buttons add a class to the body, one is font-size the other is greyscale.
I need these classes to stay on the body until clicked again to remove, as users don't want to have to keep clicking the buttons to be able to see the site.
I want to store these classes with a session or cookie, but having done some reading, sessions store cookies anyway, so whichever is the best option.
I'm using wordpress for the site, so if there's something I can use function wise, that'd be useful to know!
Can anyone help me out?
If you want to use localStorage you can use this code.
// Check if localStorage is supported
if ('localStorage' in window && typeof localStorage == 'object') {
$(document).ready(function() {
// Set the class if greyscale is set
// Note that localStorage saves everything as strings
if (localStorage["greyscale"] == "1") {
$('body').addClass('greyscale');
}
// Register click listener for the button
$('#button').click(function() {
// Toggle greyscale on and off
if (localStorage["greyscale"] != "1") {
$('body').addClass('greyscale');
localStorage["greyscale"] = "1";
}
else {
$('body').removeClass('greyscale');
localStorage["greyscale"] = "0";
}
}); // - button click
}); // - doc ready
}
JSFiddle
Session is usually using cookies but data is stored on server side and cookie is only used to identify it.
Assuming you have no reason to know if user is using gray scale on server side you can do this entirely in JS.
For example using some neat jQuery plugin for cookies https://github.com/carhartl/jquery-cookie
//set cookie and add class on button click
$('#button').click(function(){
$.cookie('greyscale', true);
$('body').addClass('greyscale');
});
//check for cookie on document load
$(function(){
if($.cookie("greyscale")){
$('body').addClass('greyscale');
}
});
Also please have in mind that this cookie will be sent to server and back over and over again so if you don't need this on server side you should use some more modern solution like HTML5 localStorage. There are few libraries that can be used to keep data on client side. They use modern features and fallback to old ones(like cookies) on older browsers. Please check http://pablotron.org/software/persist-js/ for example.
As mentioned in this answer:
The main difference being that session data is stored on the server, while cookie data is stored on the client. Therefore, a client can easily modify the cookie contents, but will have to work way harder to modify the session contents.
There are a couple ways to approach this
1) Keep the information in $_SESSION.
2) Keep the information in cookie.
Based on your case and on the data you want to store (which are not critical), I'd suggest you store it in a cookie and not bother the server to keep track for every user.
You could easily store information in a cookie via javascript.
Here is a javascript cookie reference for you:
http://www.w3schools.com/js/js_cookies.asp
After storing your info inside a cookie you could retrieve the info stored inside a cookie via javascript or php.
Keep in mind:
Javascript = client side (server wont be bothered) & after your dom is ready you will have to add the according class to your body.
PHP = server side, meaning that you wont have to add a class after the dom is ready and print your html with the appropriate class already set on the element.
PHP cookie references:
http://www.w3schools.com/php/php_cookies.asp
http://davidwalsh.name/php-cookies
Store it in a cookie.
Using cookies you can choose when will the cookie expire, when using sessions - when session is destroyed information is lost eg. when user logs off.
User will have to manually delete your cookie to delete the "body class information"

Set a cookie from view, then read it from Controller in Rails

I would like to set cookie value from within Rails view using Javascript, then use Controller to read this cookie. Is this possible with Rails, and how should I go about it?
My situation: I have an input field (say, address) that user needs to fill out when s/he first comes to my site. The user then logs in using Omniauth. I would like to persist address until after he logs in.
Update:
I was able to add to document.cookies on client. However, cookies["something"] returns nil from Rails end. Below is the cookie hash:
#<ActionDispatch::Cookies::CookieJar:0x007 #secret="f4d518c0b2", #set_cookies={}, #delete_cookies={}, #host="localhost", #secure=false, #closed=false, #cookies={"_myapp_session"=>"BAh7Ck==--776b2fcfcd63d3c84d2b1de5327e277499add6d4", "fbsr_1505068851081"=>"mqZeyvoRC"}, #signed=#<ActionDispatch::Cookies::SignedCookieJar:0x007 #parent_jar=#<ActionDispatch::Cookies::CookieJar:0x007fdf...>, #verifier=#<ActiveSupport::MessageVerifier:0x007fdfa34548d8 #secret="f4d518c0b2e9d8", #digest="SHA1", #serializer=Marshal>>>
To set a cookie in javascript you can do:
document.cookie="something= test";
So you can add an event (click, submit, ..) to get the value from the input and create a cookie the way i mentioned above.
In rails you can read the value like this:
cookies["something"]
You can also specify when the cookie will expire in javascript if you need to.
Short Answer
Install the MDN JavaScript Cookie Framework
On your js file:
docCookies.setItem('my_cookie', 'my_cookie_value', '', '/');
On your rails controller:
cookies[:my_cookie]
Not so short answer
Rails ActionDispatch::Cookies defaults the cookie path to the root of the application, while plain JavaScript defaults it to the current path.
This means that if you don't declare the path, you'll end up with two different cookies bearing the same name and a headache.
In order to troubleshoot this you can use the 'Application/Cookies' on the Chrome DevTools window so you can see all the details for each cookie and reload their values as you modify them via the 'Console' panel.
This may explain your problem. Apparently you need to make sure the cookie's path lines up.
How can i read cookies in rails that have been set by jquery

Categories