NAME
Dancer2::Plugin::CSRFI - Improved CSRF token generation and validation.
VERSION
version 1.03
SYNOPSIS
use Dancer2;
use Dancer2::Plugin::CSRFI;
set plugins => {
CSRFI => {
validate_post => 1, # this will automate token validation.
template_token => 'csrf_token', # token named 'csrf_token' will be available in templates.
}
};
get '/form' => sub {
template 'form';
};
# This route (and other post) is protected with csrf token.
post '/form' => sub {
save_data(body_parameters);
};
DESCRIPTION
This module is inspired by Dancer2::Plugin::CSRF and Plack::Middleware::CSRFBlock.
But it's fresh (2022 year release) and will be supported.
Capabilities
Сan be used in multi-application mode.
Сan issue and verify CSRF token.
Can automatically check the token for post requests.
Has useful hooks (so far one).
WHY USE CSRF TOKEN
If you are unfamiliar with this topic or want to learn more, read this Cross-Site Request Forgery Prevention Cheat Sheet.
DSL KEYWORDS
csrf_token
csrf_token(): Str
Generate CSRF token.
validate_csrf
validate_csrf(Str $token): Bool
Validate CSRF token.
CONFIGURATION
...
plugins:
CSRFI:
session_key: _csrf # this is default
refresh: 0 # this is default
template_token: csrf_token
validate_post: 0 # this is default
field_name: csrf_token # this is default
error_status: 403 # this is default
error_message: Forbidden # this is default
...
session_key
Session storage key where this module stores data.
refresh
If true, token will be refreshed on each hit. This makes your applications more secure, but in many cases, is too strict.
template_token
If provided, template token with csrf token will be set.
validate_post
If true, token will be automatically validates each post request with content-types application/x-www-form-urlencoded or multipart/form-data.
field_name
Filed name in body-parameters sent with post request, where this module will try to find csrf token, when validate_post is enabled.
error_status
Error with this status will be send if validate_post is enabled.
error_message
Error with this message will be send if validate_post is enabled.
HOOKS
after_validate_csrf
Fires if validate_post is enabled. After validating the token but before sending the error.
# Two arguments: Dancer2 app + module args.
hook after_validate_csrf => sub {
my ($app, $args) = @_;
log $args;
redirect '/error';
};
# Args structure.
$args = {
success => $success,
referer => $referer,
error_status => $error_status,
error_message => $error_message,
};
You could change $args values by ref, then module will continue to operate with the changed values.
OTHER USEFUL PLUGINS
BUGS AND LIMITATIONS
If you find one, please let me know.
SOURCE CODE REPOSITORY
https://github.com/AlexP007/dancer2-plugin-csrfi.
AUTHOR
Alexander Panteleev <alexpan at cpan dot org>.
LICENSE AND COPYRIGHT
This software is copyright (c) 2022 by Alexander Panteleev. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.