middleware static method
- HttpRequest request,
- Future<
void> next()
Verifies the CSRF token for the current request before continuing.
Behavior:
- allows read-only requests through immediately
- extracts the submitted request token
- extracts the session token from the CSRF cookie
- compares both tokens
- rejects the request with
403 Forbiddenwhen tokens are missing or do not match
Parameters:
request: The incoming HTTP request.next: The next middleware or handler in the pipeline.
Example:
await VerifyCsrfToken.middleware(request, () async {
request.response.write('Token accepted');
});
Implementation
static Future<dynamic> middleware(
HttpRequest request,
Future<void> Function() next,
) async {
if(request.uri.path.startsWith('/api/')) {
return await next();
}
if (_isReading(request)) {
return await next();
}
final token = await _getToken(request);
final sessionToken = await _getSessionToken(request);
if (token == null || sessionToken == null || token != sessionToken) {
return request.response
..statusCode = HttpStatus.forbidden
..write("403 Forbidden: Invalid CSRF Token")
..close();
}
await next();
}