KillABug KillABug - 1 year ago 84
PHP Question

Unable to decrypt CSRF/XSRF token in Laravel sent through Angular

I am using the angularavel setup for my app. On my local setup i do not need to explicitly send the

with the angular http request. And it works fine with laravel. I uploaded the same setup on the server and tried to login using my form and laravel throws a
token mismatch
error. Hence I checked the request payload in dev tools and found there is no XSRF-TOKEN header in the request,like I see on my local. I believe angular generates one by default and send it with every http request,but not sure why is it failing here.

I added the csrf token in angular based on this tutorial here using the meta tag method. my meta is
<meta name="csrf-token" content='<?php echo json_encode(csrf_token()); ?>'> // Also tried without encoding

In my .config I have

$httpProvider.defaults.headers.common['X-XSRF-TOKEN'] = $('meta[name=csrf-token]').attr('content');

If I use
I get DecryptException in Encrypter.php line 142:Invalid data.
If I use
I get Token Mismatch error.
My request shows the token in the header(added below).

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36 FirePHP/4Chrome
X-XSRF-TOKEN:InhRWmVjcUxZNWVMRWlrWmFXR09vbGdZT1M2Z284c0NqV2x2RWxaN0Mi -->token

Where am I commiting mistake? Also the defult token from angular seems to be integrated and a vry large string.whereas the one genrated by function is a small string.

Answer Source

This is what worked for me, I'll show you the relevant snippets.

In my template I have the following:

<script type="text/javascript">myApp.constant("CSRF_TOKEN", '<?= csrf_token() ?>');</script>

And I have a factory such as:

.factory('Product', function($http, CSRF_TOKEN) {    
    return {
        // store a product
        save : function(productData) {            
            return $http({
                method: 'POST',
                url: 'http://localhost/angularjs/public/api/products',
                headers: {'X-CSRF-TOKEN': CSRF_TOKEN},
                data: productData

This is all I needed to do to stop receiving csrf token related errors.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download