I am using the angularavel setup for my app. On my local setup i do not need to explicitly send the XSRF-TOKEN
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 X-XSRF-TOKEN
I get DecryptException in Encrypter.php line 142:Invalid data.
If I use X-CSRF-TOKEN
I get Token Mismatch error.
My request shows the token in the header(added below).
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:68
Content-Type:application/json;charset=UTF-8
Cookie:PHPSESSID=ySsuvCYycB-9IfZZ29kSF1
Host:demo.abc.com
Origin:http://demo.abc.com
Referer:http://demo.abc.com/hexa/public/
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-FirePHP-Version:0.0.6
X-Wf-Max-Combined-Size:261120
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.
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.