CSRF protection
secret_csrf, $.csrf(), @{csrf}, DEF.onCSRFcreate and DEF.onCSRFcheck.
On this page
The configuration keys, the methods and the delegates of CSRF tokens. The guide CSRF protection explains how to protect a form, an API and a WebSocket.
API
config
secret_csrf : String
The key of the CSRF tokens.
secret_csrf : StringReturns String
The key that encrypts the token. With an empty value $.csrf() returns an empty string and DEF.onCSRFcheck() returns true for every request. The lifetime of a token is in $csrfexpiration (see Configuration).
Default: ''.
secret_csrf : a-long-random-text
$csrfexpiration : 2 hours
command
@{csrf}
Prints a CSRF token in a view.
@{csrf}The same token as $.csrf() (see Controller). In a view rendered without a controller it prints nothing.
<form action="/contact/?csrf=@{csrf}" method="POST">
<input type="text" name="name" />
<button>Send</button>
</form>
delegate
DEF.onCSRFcreate = function($)
Creates the token of $.csrf() and @{csrf}.
DEF.onCSRFcreate = function($)| Parameter | Type | Description |
|---|---|---|
$ |
Controller |
The request. |
Returns String The token.
The default function encrypts the IP address, a hash of the User-Agent header and the expiration with CONF.secret_csrf. Replace it together with DEF.onCSRFcheck.
DEF.onCSRFcreate = function($) {
return ENCRYPT({ id: $.sessionid, expire: NOW.add('2 hours').getTime() }, CONF.secret_csrf);
};
delegate
DEF.onCSRFcheck = function($)
Checks the token of a request.
DEF.onCSRFcheck = function($)| Parameter | Type | Description |
|---|---|---|
$ |
Controller |
The request. |
Returns Boolean true when the request is allowed.
The default function reads the header x-csrf-token or the query argument csrf, decrypts it and compares the IP address, the browser and the expiration. Without CONF.secret_csrf it returns true. The framework calls it only for WebSocket routes with the flag @csrf: a refused client is disconnected. In HTTP routes call it from a middleware.
MIDDLEWARE('csrf', function($, next) {
if (DEF.onCSRFcheck($))
next();
else
$.invalid(403);
});
ROUTE('POST /contact/ #csrf', $ => $.success());