Search code examples
angularjslaravelcsrfrestangular

Correctly set headers for Laravel 5 CSRF Token


Alright, been searching this one for hours and just can't find the start of a solution.

I am using an angularJS frontend with a laravel backend. Restangular is my communcation service.

My POST are fine, because I can include the _token in the data and it will work.

But for Restangular to call a destroy function it looks like...

Restangular.all('auth/logout').remove(); //maps to AuthController@Destroy

All fine, but then you will get a TOKENMISMATCH Exception, which is a good security messure

Since I can't find a way to include the _token into the remove, since it's body-less essentially, I decided to put the token in the header.

RestangularProvider.setDefaultHeaders({'X-XSRF-TOKEN': CSRF_TOKEN}); //CSRF_TOKEN gathered elsewhere

Out of the Chrome dev tolos, I can see the header is set to

X-XSRF-TOKEN:ClkQIRLpFQgMg8ZT6X5CF6doCplRfdJzW8msx2JI

X-XSRF-TOKEN is exactly what the VerifyCrsfToken.php is looking for. Yet, it spits out a decrypt error. Any other token name, such as XSRF-TOKEN, _TOKEN, CSRF_TOKEN all spit out token mismatch.

Because of that last fact, it seems like the header is declared correctly, but something beyond my comprehension is causing Laravel to fail the decrypt. And I've closely at the decrypt function, but don't understand why it'd fail...

Thank you for your help.


Solution

  • This is due to encryption of the csrf token. Laravel expect the token to be encrypted.

    It tries to decrypt the the plain token you provide and it fails.

    Before you can use the token in the header you have to encrypt it.

    $encrypter = app('Illuminate\Encryption\Encrypter');
    $encrypted_token = $encrypter->encrypt(csrf_token());
    

    That did the trick for me.

    Alex