---
title: Protezione CSRF
project: Total.js V5
version: 0.0.20
section: reference
language: it
license: MIT
url: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/csrf/
updated: 2026-12-02T17:11:30.727Z
---

# Protezione CSRF

> secret_csrf, $.csrf(), @{csrf}, DEF.onCSRFcreate e DEF.onCSRFcheck.

Le chiavi di configurazione, i metodi e i delegate dei token CSRF. La guida [Protezione CSRF](../../guides/csrf/) spiega come proteggere un modulo, un'API e un WebSocket.

## API

### secret_csrf : String

Type: `config`

La chiave dei token CSRF.

Returns: `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](../../reference/configuration/)).

Default: `''`.

Example: Nel file di configurazione
```text
secret_csrf     : a-long-random-text
$csrfexpiration : 2 hours
```

### @{csrf}

Type: `command`

Stampa un token CSRF in una vista.

Lo stesso token di `$.csrf()` (vedi [Controller](../../reference/controller/)). In una vista renderizzata senza un controller non stampa nulla.

Example: Un modulo
```html
<form action="/contact/?csrf=@{csrf}" method="POST">
	<input type="text" name="name" />
	<button>Send</button>
</form>
```

### DEF.onCSRFcreate = function($)

Type: `delegate`

Crea il token di $.csrf() e @{csrf}.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Controller` | yes |  | La richiesta. |

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

Example: Un token della sessione
```js
DEF.onCSRFcreate = function($) {
	return ENCRYPT({ id: $.sessionid, expire: NOW.add('2 hours').getTime() }, CONF.secret_csrf);
};
```

### DEF.onCSRFcheck = function($)

Type: `delegate`

Controlla il token di una richiesta.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Controller` | yes |  | La richiesta. |

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

Example: Un middleware
```js
MIDDLEWARE('csrf', function($, next) {
	if (DEF.onCSRFcheck($))
		next();
	else
		$.invalid(403);
});

ROUTE('POST /contact/ #csrf', $ => $.success());
```
