CSRF Protection

Apply CSRF protection to browser routes that change data and rely on session cookies. Atom pairs a token stored in the session with a token sent by the form. The middleware checks that pair before the handler runs.

Protect Routes

Attach CsrfMiddleware to an existing route. Here $saveArticle is the application's handler. You can also call middleware() on a route group to apply the same protection to its routes.

use Atom\Router\Route;
use Atom\Security\CsrfMiddleware;

Route::post("/articles", $saveArticle)
    ->middleware(CsrfMiddleware::class);

For an Atom page, declare the middleware on #[PageRoute]. Atom attaches it to the page's render route and its action routes.

use Atom\Page\PageRoute;
use Atom\Security\CsrfMiddleware;

#[PageRoute("/articles/edit", middleware: CsrfMiddleware::class)]

Place the attribute above the page class. The example below assumes that class already has a save page action.

HTML forms

Inject Atom\Security\CsrfTokenManagerInterface into the page and expose its token() result to the template. It returns the session's current token, creating one if needed.

ArticlesPage.php (excerpt)
use Atom\Security\CsrfTokenManagerInterface;

// Inside ArticlesPage.
public function __construct(private readonly CsrfTokenManagerInterface $csrf)
{
}

public function csrfToken(): string
{
    return $this->csrf->token();
}

Include the token in a hidden _token field. The _action field names the page action for an ordinary form submission, and atom:submit names it for an enhanced one.

ArticlesPage.atom.html (excerpt)
<form method="post" atom:submit="save">
    <input type="hidden" name="_action" value="save">
    <input type="hidden" name="_token" value="{{ $this->csrfToken() }}">
    <label>Title <input name="title"></label>
    <button type="submit">Save</button>
</form>

What Atom checks on submission

  1. GET, HEAD, and OPTIONS pass through the CSRF middleware without a token check.
  2. For other methods, Atom reads X-CSRF-Token first. If the header is absent or empty, it reads the _token form field.
  3. The token must match the one in the current session. If it is missing or invalid, Atom returns 403 Forbidden before the route handler or page action runs.

For a standalone atom:action control, you can expose the token in <meta name="csrf-token"> in the layout. The Atom client sends it as X-CSRF-Token on enhanced requests that need a token.