Protezione CSRF
secret_csrf, $.csrf(), @{csrf}, DEF.onCSRFcreate e DEF.onCSRFcheck.
In questa pagina
Le chiavi di configurazione, i metodi e i delegate dei token CSRF. La guida Protezione CSRF spiega come proteggere un modulo, un'API e un WebSocket.
API
config
secret_csrf : String
La chiave dei token CSRF.
secret_csrf : StringRestituisce String
La chiave che cifra il token. Con un valore vuoto $.csrf() restituisce una stringa vuota e DEF.onCSRFcheck() restituisce true per ogni richiesta. La durata di un token è in $csrfexpiration (vedi Configurazione).
Default: ''.
secret_csrf : a-long-random-text
$csrfexpiration : 2 hours
command
@{csrf}
Stampa un token CSRF in una vista.
@{csrf}Lo stesso token di $.csrf() (vedi Controller). In una vista renderizzata senza un controller non stampa nulla.
<form action="/contact/?csrf=@{csrf}" method="POST">
<input type="text" name="name" />
<button>Send</button>
</form>
delegate
DEF.onCSRFcreate = function($)
Crea il token di $.csrf() e @{csrf}.
DEF.onCSRFcreate = function($)| Parametro | Tipo | Descrizione |
|---|---|---|
$ |
Controller |
La richiesta. |
Restituisce String Il token.
La funzione predefinita cifra con CONF.secret_csrf l'indirizzo IP, un hash dell'header User-Agent e la scadenza. Sostituiscila insieme a DEF.onCSRFcheck.
DEF.onCSRFcreate = function($) {
return ENCRYPT({ id: $.sessionid, expire: NOW.add('2 hours').getTime() }, CONF.secret_csrf);
};
delegate
DEF.onCSRFcheck = function($)
Controlla il token di una richiesta.
DEF.onCSRFcheck = function($)| Parametro | Tipo | Descrizione |
|---|---|---|
$ |
Controller |
La richiesta. |
Restituisce Boolean true quando la richiesta è consentita.
La funzione predefinita legge l'header x-csrf-token o l'argomento csrf della query string, lo decifra e confronta l'indirizzo IP, il browser e la scadenza. Senza CONF.secret_csrf restituisce true. Il framework la chiama solo per le route WebSocket con il flag @csrf: un client rifiutato viene disconnesso. Nelle route HTTP chiamala da un middleware.
MIDDLEWARE('csrf', function($, next) {
if (DEF.onCSRFcheck($))
next();
else
$.invalid(403);
});
ROUTE('POST /contact/ #csrf', $ => $.success());