# Token legati a un browser con ENCRYPTREQ() e DECRYPTREQ()

> Cifra un valore insieme allo user agent (e facoltativamente all'indirizzo IP) della richiesta e rileggilo solo dallo stesso client.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: it
Content-SHA256: 6d793e5bc34efd875ec901297bde01bcb107ac3c643a0e68c1310e828f934566
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

`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.

```js controllers/tokens.js
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 });
}
```
