Token legati a un browser con ENCRYPTREQ() e DECRYPTREQ()
ENCRYPTREQ($, value, key, [strict]) cifra un valore insieme allo user agent della richiesta e restituisce un token di testo. DECRYPTREQ($, token, key) rilegge il valore e non restituisce nulla (undefined) quando la chiave è sbagliata, il token è vuoto o la richiesta arriva da un client diverso. Con strict impostato su true anche l'indirizzo IP della richiesta fa parte del token, quindi smette di funzionare anche quando l'indirizzo cambia.
Usalo per valori che consegni al browser e ti aspetti di ricevere indietro dallo stesso browser: un link di breve durata, un indirizzo di download, un token di modulo. Non sostituisce una sessione: lo user agent è facile da copiare. Per i token che non dipendono dalla richiesta vedi la ricetta su cifratura e decifratura.
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 });
}