Skip to content

Commit

Permalink
added support for the X-CSRF-Token request header
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Dec 4, 2013
1 parent 71738ba commit 490e48b
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
11 changes: 7 additions & 4 deletions lib/Mojolicious/Controller.pm
Expand Up @@ -416,11 +416,14 @@ sub url_for {
}

sub validation {
my $self = shift;
my $token = $self->session->{csrf_token};
my $self = shift;

my $req = $self->req;
my $hash = $req->params->to_hash;
$hash->{csrf_token} //= $req->headers->header('X-CSRF-Token')
if my $token = $self->session->{csrf_token};
return $self->stash->{'mojo.validation'}
||= $self->app->validator->validation->input($self->req->params->to_hash)
->csrf_token($token);
||= $self->app->validator->validation->input($hash)->csrf_token($token);
}

sub write {
Expand Down
2 changes: 2 additions & 0 deletions lib/Mojolicious/Guides/Rendering.pod
Expand Up @@ -784,6 +784,8 @@ validate it with L<Mojolicious::Validator::Validation/"csrf_protect">.
</body>
</html>

The token can also be submitted with the C<X-CSRF-Token> request header.

=head2 Adding helpers

Adding and redefining helpers is very easy, you can use them to do pretty much
Expand Down
9 changes: 9 additions & 0 deletions t/mojolicious/validation_lite_app.t
Expand Up @@ -184,6 +184,15 @@ $t->post_ok('/forgery' => form => {csrf_token => $token, foo => 'bar'})
->status_is(200)->content_unlike(qr/Wrong or missing CSRF token!/)
->element_exists('[value=bar]');

# Correct CSRF token (header)
$t->post_ok('/forgery' => {'X-CSRF-Token' => $token} => form => {foo => 'bar'})
->status_is(200)->content_unlike(qr/Wrong or missing CSRF token!/)
->element_exists('[value=bar]');

# Wrong CSRF token (header)
$t->post_ok('/forgery' => {'X-CSRF-Token' => 'abc'} => form => {foo => 'bar'})
->status_is(200)->content_like(qr/Wrong or missing CSRF token!/);

# Missing CSRF token again
$t->post_ok('/forgery' => form => {foo => 'bar'})->status_is(200)
->content_like(qr/Wrong or missing CSRF token!/);
Expand Down

0 comments on commit 490e48b

Please sign in to comment.