I’m attempting to make a simple set of functions to handle cookies. They will only be used to store and retrieve an auth token for accessing an external API.
I’m keeping it simple and using some cookie defaults. I expect them to expire at browser close and be restricted to the setting domain only. I definitely want to know if I got either of those wrong or if there are other defaults that might affect things.
I’m aware of CSRF/XSRF and would love suggestions to better protect against that. This is currently part of a simple client-side SPA with JQuery as the only library and I’d like to keep it that way, but am open to suggestions for adjustments that could improve security with minimal changes to those restrictions (the simpler the better).
Beyond that, I’m also looking for any suggestions to improve readability, how well the code follows standard practices, how well it’s documented with comments and variable names, etc.
// Creates a cookie that gets erased when the // browser window is closed and defaults // to the current domain. // It's also set to secure for good measure // (even though it's not expected to be // transmitted anyway). function createSessionCookie(name, value) { document.cookie = name+"="+value+"; path=/ ; secure"; } // Helper for reading cookie values easily // Returns a value or null if name isn't found function readCookie(name) { var nameEq = name + "="; var cookies = document.cookie.split(';'); for (var cookieNum = 0; cookieNum < cookies.length; cookieNum++) { var currentCookie = cookies[cookieNum]; while (currentCookie.charAt(0) === ' ') { currentCookie = currentCookie.substring(1, currentCookie.length); } if (currentCookie.indexOf(nameEq) === 0) { return currentCookie.substring(nameEq.length, currentCookie.length); } } return null; }