Core\Csrf::token
Returns a CSRF token for the visitor's session. CSRF (cross-site request forgery) is an attack where another website sends a form in the visitor's name. You put the token in your form, and the server checks it when the form comes back.
Set [http] csrf_key in nvs.toml. Without it, token() throws a RuntimeError. Outside a web request, token() throws a LogicError.
For a new visitor, the response sends a session cookie with the token. The server saves no session data until your program writes a value with Core\Session. So a login form for a new visitor also has a valid token.
Send the token back in a form field named _csrf or in the x-csrf-token header. The server checks it before your route method runs. A request without a valid token gets the status 403. The token is valid only with the session cookie that was sent with it.
Every call returns a different token. All of them stay valid, so a form open in a second tab still works.
The examples below show a form for a new visitor, the form sent back with and without its token, and the error in a command-line program.
Return value
Returns string. The token. Every call returns a different string, and each one is valid for the whole session. It uses only A-Za-z0-9-_, so you can put it in a form field, a header or a URL without encoding it.
Errors
LogicErrorThe program is not handling a request. A command-line program, a job and a test have no session.RuntimeError[http] csrf_keyis not set.RuntimeErrorThe session store, where the server keeps session data, cannot be opened. This happens only at the first call in the request that uses the session. With the default store, the cause is that the server has no data folder. With[session] backend = "shared",[cache.shared] urlis not set, or the program does not have thecache.sharedcapability.IOErrorThe store cannot be reached. The user may still have a session there, so do not treat them as signed out.LogicErrorThe call runs inside a function passed toCore\Task::runAfterResponse, after the response was sent. The session cookie cannot be sent then.
Changelog
| Version | Change |
|---|---|
0.0.5 | Core\Csrf::token and the Core\Passkey methods that save or check a challenge open the session on their first use. You do not call anything before them. In a program that handles no request, they throw a LogicError. |
0.0.6 | Core\Csrf::token saves no session data for a new visitor. The response still sends the session cookie, and the server accepts the token on the next request. The server saves session data only when the program writes a value with Core\Session. |
Examples
The examples below run with this configuration file.
# The server checks CSRF tokens with this key. These examples use a fixed key.# Your own key is 32 random bytes, written in base64.[http]csrf_key = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc"A token on a first visit
<?nvs// Shows a contact page that puts a CSRF token in its form, for a visitor who has no session yet.use Core\Http\Method;
class Contact{ #[Core\Route(path: '/contact', method: Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public function form(): void { string $token = Core\Csrf::token(); echo html`<form method="post" action="/contact"><input type="hidden" name="_csrf" value="{$token}"><textarea name="message"></textarea><button>Send</button></form>`; }}
class Gate implements Core\Router\Gate{ public function allows(Core\Router\Match $route): bool { return true; }
public function refused(Core\Router\Refusal $reason, ?Core\Router\Match $route): void { echo 'You cannot open this page.'; }
public function failed(?Core\Router\Match $route, ?Throwable $error): void { echo 'Something went wrong.'; }}
if (Core\Env::context() == Core\Env::Context::Request) { Core\Router::dispatch(new Gate());} else { // This request sends no cookie, as a first visit does. var $page = Core\Test::request(Method::Get, '/contact'); echo 'status: ', $page->status(), "\n";
// `token()` makes a session identifier. The response sends it in the `nvsid` cookie, so this prints `yes`. string $session = $page->cookies()['nvsid'] ?? ''; echo 'session cookie sent: ', $session != '' ? 'yes' : 'no', "\n";
// The token is different on every visit, so this prints only that the form has one. string $body = $page->body() as string; echo 'form has a token: ', Core\Str::contains($body, 'name="_csrf" value="') ? 'yes' : 'no', "\n";}status: 200session cookie sent: yesform has a token: yesThe token passes on the next request
<?nvs// Shows a form that is sent back with its token, and the same form sent without one.use Core\Http\Method;
class Contact{ #[Core\Route(path: '/contact', method: Method::Get)] #[Core\Access(allow: Core\Audience::Public)] public function form(): void { echo Core\Csrf::token(); }
#[Core\Route(path: '/contact', method: Method::Post)] #[Core\Access(allow: Core\Audience::Public)] public function send(): void { echo 'Thank you. Your message was sent.'; }}
class Gate implements Core\Router\Gate{ public function allows(Core\Router\Match $route): bool { return true; }
// The server calls this method when a form arrives without a valid token. public function refused(Core\Router\Refusal $reason, ?Core\Router\Match $route): void { echo $reason == Core\Router\Refusal::Csrf ? 'This form has expired. Please reload the page.' : 'Not found.'; }
public function failed(?Core\Router\Match $route, ?Throwable $error): void { echo 'Something went wrong.'; }}
if (Core\Env::context() == Core\Env::Context::Request) { Core\Router::dispatch(new Gate());} else { // The first request shows the form. Here the page prints only the token. var $page = Core\Test::request(Method::Get, '/contact'); string $session = $page->cookies()['nvsid'] ?? ''; string $token = $page->body() as string;
// The browser sends the cookie back, and the form sends the token in its `_csrf` field. // The server checks the token before `send()` runs. This prints `200`. array<string> $headers = [ 'cookie' => 'nvsid=' . $session, 'content-type' => 'application/x-www-form-urlencoded', ]; var $sent = Core\Test::request(Method::Post, '/contact', { headers: $headers, body: '_csrf=' . $token . '&message=Hello' }); echo $sent->status(), ' ', $sent->body(), "\n";
// The same form without the token. `send()` does not run, and this prints `403`. var $forged = Core\Test::request(Method::Post, '/contact', { headers: $headers, body: 'message=Hello' }); echo $forged->status(), ' ', $forged->body(), "\n";}200 Thank you. Your message was sent.403 This form has expired. Please reload the page.A token outside a request throws
<?nvs// Shows that `token()` works only while the program answers a web request.
// This program runs from the command line, so it has no visitor and no session.// `token()` throws a `LogicError`.try { echo Core\Csrf::token();} catch (LogicError $e) { echo "no request: LogicError\n";}no request: LogicError