Tokens tied to a browser with ENCRYPTREQ() and DECRYPTREQ()
ENCRYPTREQ($, value, key, [strict]) encrypts a value together with the user agent of the request and returns a text token. DECRYPTREQ($, token, key) reads the value back, and returns nothing (undefined) when the key is wrong, the token is empty, or the request comes from a different client. With strict set to true the IP address of the request is part of the token too, so it also stops working when the address changes.
Use it for values that you hand to the browser and expect back from the same browser: a short-lived link, a download address, a form token. It is not a replacement for a session: the user agent is easy to copy. For tokens that do not depend on the request see the encrypt and decrypt recipe.
exports.install = function() {
ROUTE('GET /issue/', issue);
ROUTE('GET /read/', read);
ROUTE('GET /read-wrong-key/', wrongkey);
};
function issue($) {
$.json({ token: ENCRYPTREQ($, { id: 5 }, 'my-secret'), strict: ENCRYPTREQ($, 'only-here', 'my-secret', true) });
}
function read($) {
$.json({ value: DECRYPTREQ($, $.query.token, 'my-secret') || null });
}
function wrongkey($) {
$.json({ value: DECRYPTREQ($, $.query.token, 'another-secret') || null });
}