A client-side session stores the complete session state, including the user identifier, in a cookie sent to the browser. Each server receiving that cookie can recover the state without consulting a shared session store, which can improve scalability. section 9.3
The convenience creates a security question: what happens if a user edits the cookie? An attacker could replace a username and impersonate another user unless the server can detect tampering. Digitally sign or encrypt the session cookie, and validate its signature before trusting the contents. section 9.10 section 9.3
Express.js session data
An Express.js application can use cookie-parser to place session data in the cookie, then read it on a later request: one route stores username = 'John', and another retrieves request.session.username. The cookie must be treated as untrusted until its signature is verified. section 9.3 section 9.10
Protect client-side sessions by:
- Using a maintained session-management framework and enabling digital signatures or encryption. section 9.11
- Setting Secure for HTTPS delivery and HttpOnly to block browser JavaScript access. section 9.11
- Avoiding sensitive information that the user should not see, because signed session contents remain readable by the client. section 9.10
/**
* Unsign and decode the given `input` with `secret`,
* returning `false` if the signature is invalid.
*/
exports.unsign = function(input, secret){
var tentativeValue = input.slice(0, input.lastIndexOf('.')),
expectedInput = exports.sign(tentativeValue, secret),
expectedBuffer = Buffer.from(expectedInput),
inputBuffer = Buffer.from(input);
return (
expectedBuffer.length === inputBuffer.length &&
crypto.timingSafeEqual(expectedBuffer, inputBuffer)
) ? tentativeValue : false;
};
Inspect the signature-checking implementation that rejects modified cookie values using a timing-safe comparison. section 9.10
