Security / Request Validation

CSRF Protection

Cross-Site Request Forgery (CSRF) is a malicious exploit whereby unauthorized commands are transmitted from a user that the web application trusts.

Archery makes it incredibly simple to protect your application from CSRF attacks by automatically generating and verifying tokens for every active user session.

Generating Tokens

Behind the scenes, the Archery StartSession middleware attaches a cryptographically secure token to every visitor's session cookie.

To protect your form submissions, you simply need to include this token as a hidden input field named _token. Because Archery populates template views with session data, you can achieve this easily using your templating engine:

<form method="POST" action="/profile">
    
  <!-- Include the CSRF token -->
  @csrf
  
  <input type="text" name="name" />
  <button type="submit">Save Settings</button>
</form>

Verifying Tokens

To enforce CSRF protection, attach the VerifyCsrfToken.middleware to your routes or route groups.

The middleware intercepts the request and verifies that the _token submitted in the form body matches the token stored in the user's archery_csrf_token cookie.

router.post(
  '/profile',
  handler: (request) async => profileController.update(request),
  middleware: [VerifyCsrfToken.middleware],
);

Skipped Requests

You do not need to worry about CSRF verification blocking reads or intercepting API clients. The middleware intentionally skips verification for:

  1. "Read" methods: GETHEAD, and OPTIONS.
  2. Any route URI beginning with /api/.