The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Mojolicious::Plugin::CSRFDefender - Defend CSRF automatically in Mojolicious Application

VERSION

This document describes Mojolicious::Plugin::CSRFDefender.

SYNOPSIS

# Mojolicious
$self->plugin('Mojolicious::Plugin::CSRFDefender');

# Mojolicious::Lite
plugin 'Mojolicious::Plugin::CSRFDefender';

DESCRIPTION

This plugin defends CSRF automatically in Mojolicious Application. Following is the strategy.

output filter

When the application response body contains form tags with method="post", this inserts hidden input tag that contains token string into forms in the response body. For example, the application response body is

<html>
  <body>
    <form method="post" action="/get">
      <input name="text" />
      <input type="submit" value="send" />
    </form>
  </body>
</html>

this becomes

<html>
  <body>
    <form method="post" action="/get">
    <input type="hidden" name="csrf_token" value="zxjkzX9RnCYwlloVtOVGCfbwjrwWZgWr" />
      <input name="text" />
      <input type="submit" value="send" />
    </form>
  </body>
</html>

input check

For every POST requests, this module checks input parameters contain the collect token parameter. If not found, throws 403 Forbidden.

OPTIONS

plugin 'Mojolicious::Plugin::CSRFDefender' => {
    parameter_name => 'param-csrftoken',
    session_key    => 'session-csrftoken',
    token_length   => 40,
    error_status   => 400,
    error_template => 'public/400.html',
};
parameter_name(default:"csrftoken")

Name of the input tag for the token.

session_key(default:"csrftoken")

Name of the session key for the token.

token_length(default:32)

Length of the token string.

error_status(default:403)

Status code when CSRF is detected.

error_content(default:"Forbidden")

Content body when CSRF is detected.

error_template

Return content of the specified file as content body when CSRF is detected. Specify the file path from the application home directory.

onetime(default:0)

If specified with 1, this plugin uses onetime token, that is, whenever client sent collect token and this middleware detect that, token string is regenerated.

METHODS

Mojolicious::Plugin::CSRFDefender inherits all methods from Mojolicious::Plugin and implements the following new ones.

register

$plugin->register;

Register plugin in Mojolicious application.

SEE ALSO

REPOSITORY

https://github.com/shibayu36/p5-Mojolicious-Plugin-CSRFDefender

AUTHOR

C<< <shibayu36 {at} gmail.com> >>

LICENCE AND COPYRIGHT

Copyright (c) 2011, Yuki Shibazaki <shibayu36 {at} gmail.com>. All rights reserved.

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic.