N
N
naneri2014-08-12 11:05:19
Angular
naneri, 2014-08-12 11:05:19

How to rewrite CSRF filter in Laravel for Angular?

I want to correctly rewrite the CSRF filter in Laravel to work with AngularJS.
At the moment it looks like this:

Route::filter('csrf', function()
{
  if (Session::token() != Input::get('_token'))
  {
    throw new Illuminate\Session\TokenMismatchException;
  }
});

But it doesn't work for Ajax requests.
Jquery can rewrite the filter by adding CSRF to the Header of each request:
$.ajaxSetup({
   headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});

And process it:
Route::filter('csrf', function() 
{
    $token = Request::ajax() ? Request::header('X-CSRF-Token') : Input::get('_token');
    if (Session::token() != $token){
        throw new Illuminate\Session\TokenMismatchException;
    }
});

How to properly rewrite for Angularjs?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vyacheslav Plisko, 2014-08-12
@naneri

app.config([
        "$httpProvider", function($httpProvider) {
             $httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=_token]').attr('content');
        }
]);

M
Mikhail Osher, 2014-08-12
@miraage

I'll tell you how they do it in Rails - and you draw an analogy.
add XSRF-TOKEN cookie with value Session::token()
In CSRF validation method (only for POST, PUT, PATCH, DELETE requests):

Request::header('X-XSRF-TOKEN') == Session::token()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question