How to use Plack::Middleware::CSRFBlock with Dancer?

728 views Asked by At

I want to protect all forms from CSRF with Dancer.

I tried using Plack::Middleware::CSRFBlock, but the error said "CSRFBlock needs Session.". Even if I use Plack::Session, forms didn't have a hidden input field that contains one time token.

Are there any good practice to do this? Any advice much appreciated.

my environment/development.yml is:

# configuration file for development environment

# the logger engine to use
# console: log messages to STDOUT (your console where you started the
#          application server)
# file:    log message to a file in log/
logger: "console"

# the log level for this environment
# core is the lowest, it shows Dancer's core log messages as well as yours
# (debug, info, warning and error)
log: "core"

# should Dancer consider warnings as critical errors?
warnings: 1

# should Dancer show a stacktrace when an error is caught?
show_errors: 1

# auto_reload is a development and experimental feature
# you should enable it by yourself if you want it
# Module::Refresh is needed 
# 
# Be aware it's unstable and may cause a memory leak.
# DO NOT EVER USE THIS FEATURE IN PRODUCTION 
# OR TINY KITTENS SHALL DIE WITH LOTS OF SUFFERING
auto_reload: 0

session: Simple
#session: YAML

plack_middlewares:
    -
        #- Session
        - CSRFBlock
        - Debug
        - panels
        -
            - Parameters
            - Dancer::Version
            - Dancer::Settings
            - Memory

and the route is:

get '/test' => sub {
    return <<EOM
        <!DOCTYPE html>
        <html>
        <head><title>test route</title></head>
        <body>
            <form action="./foobar" method="post">
            <input type="text"/>
            <input type="submit"/>
            </form>
        </body>
        </html>
EOM
};
1

There are 1 answers

1
so not liopa On BEST ANSWER

Well, I noticed the Debug panel isn't shown, meaning Plack::Middlewares::Debug isn't loaded. With help from How to use Dancer with Plack middlewares | PerlDancer Advent Calendar and Plack::Middleware::Debug::Dancer::Version I managed to turn it on

session: PSGI
## Dancer::Session::PSGI

plack_middlewares:
    -
        - Session
    -
        - CSRFBlock
    -
        - Debug
## panels is an argument for Debug, as in 
## enable 'Debug', panels => [ qw( Parameters Response Environment Session Timer Dancer::Logger Dancer::Settings Dancer::Version ) ];
        - panels
        -
            - Parameters
            - Response
            - Environment
            - Session
            - Timer
            - Dancer::Logger
            - Dancer::Settings
            - Dancer::Version
#Plack::Middleware::Debug::Dancer::Version