Short answer: I will remove the part about CSRF tokens from the documentation. If you are building a simple application, you probably don't need them, and can simply use cookies with same_site=strict which are the default in the latest version of SQLPage. That is, you don't have to worry about CSRF attacks and SQLPage will protect you against them by default, unless you are doing something very unusual.
Long answer
CSRF
Cross-site request forgery is an attack where an attacker creates a malicious website that points to your website. When users click on a link in the malicious site, their browser makes a request which contains their session token to your website, and your website processes the request as if the user legitimately wanted to perform the action.
Traditional protection against CSRF
Traditionally, websites started to implement CSRF tokens to protect against this attack.
The website would generate a random token (in sqlpage, you could use sqlpage.random_string), and store it both in the database (using a simple insert) and in a hidden field in the protected form. On the page that handled the form submission, one would check that the csrf token sent by the user matched the one that was stored in the database. In SQLPage, one could do that with
select 'redirect' as component, '/error.sql' as link where not exists (select 1 from tokens where session = sqlpage.cookie('session') and token = :csrf_token)
Modern development
Since around 2018, all browsers support the samesite=strict cookie attribute, and since v0.17, SQLPage sets it by default on all cookies. What this means is that if your session token is stored in a cookie, it won't be sent with the request coming from a malicious website. In this case, your normal authentication mechanism, that just checks for the session cookie is enough:
select 'redirect' as component, '/signin.sql' as link where not exists (select 1 from user_sessions where session_token = sqlpage.cookie('session'))
I hope this answer is clear.
If you want more details, including cases in which you may still want to implement CSRF tokens, check out this question on stackexchange. In short the reasons to still implement csrf tokens in 2023 are:
- if you want to implement "defense in depth" because your website is highly sensitive
- if you know some of your users use (very) outdated browsers
- if you generate custom links based on user data (
select some_user_generated_data as link) and perform sensitive actions based on url parameters instead of form data variables:delete from my_table where id = $id_to_deleteinstead ofdelete from my_table where id = :id_to_delete.