spark_csrf
CSRF protection middleware for Spark applications.
Features
- Automatic CSRF token generation and validation
- Protects unsafe HTTP methods (POST, PUT, PATCH, DELETE)
- Safe methods pass through without validation (GET, HEAD, OPTIONS)
- Token stored in session, validated from request header
- Configurable header name and session key
Installation
dependencies:
spark_csrf: ^1.0.0Requires: spark_session middleware must be applied before spark_csrf.
Usage
Basic Setup
import 'package:spark_csrf/spark_csrf.dart';
import 'package:spark_session/spark_session.dart';
final handler = Pipeline()
.addMiddleware(sessionMiddleware(store: InMemorySessionStore()))
.addMiddleware(csrfMiddleware())
.addHandler(myRouter);Custom Configuration
csrfMiddleware(
headerName: 'X-CSRF-Token', // default
sessionKey: 'csrf_token', // default
)How It Works
- On the first request, a secure 48-character hex token is generated and stored in the session
- Your application reads the token from the session and includes it in forms or JavaScript
- For POST, PUT, PATCH, and DELETE requests, the middleware validates the X-CSRF-Token header
- Returns 403 Forbidden if the token is missing or does not match
Client-Side Integration
fetch('/api/resource', {
method: 'POST',
headers: {
'X-CSRF-Token': csrfToken,
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});