I am following this article http://blog.neoxia.com/laravel4-and-angularjs/ to set up and filter the CSRF token. I am able to make it working on local server but after I deployed live and tested it, I keep getting "status code 418". Any idea?
Below is my code:
Route.php:
// Route to filter CSRF
Route::filter('serviceCSRF',function(){
if (Session::token() != Request::header('csrf_token')) {
return Response::json([
'message' => 'Security token doesn\'t match, possible CSRF attack.'
], 418);
}
});
// Route for authentication
Route::group(['prefix' => 'api/auth', 'after' => 'allowOrigin'], function() {
Route::get('check', [
'as'=>'check_auth_path',
'uses'=>'SessionsController@check'
]);
Route::post('login', [
'as'=>'login_path',
'uses'=>'SessionsController@login'
]);
Route::get('sentryLogout', [
'as'=>'logout_path',
'uses'=>'SessionsController@logout'
]);
});
Session Controller:
class SessionsController extends \BaseController {
public function __construct() {
$this->beforeFilter('serviceCSRF');
}
...
app.js:
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "//" + window.location.hostname + "/api/csrf", false);
xhReq.send(null);
app.constant("CSRF_TOKEN", xhReq.responseText);
app.run(function ($window, $couchPotato, $rootScope, $state, $stateParams, $http, CSRF_TOKEN) {
app.lazy = $couchPotato;
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
// editableOptions.theme = 'bs3';
$http.defaults.headers.common['csrf_token'] = CSRF_TOKEN;
// watch for location path change
$rootScope.$on("$locationChangeStart",function() {
....
Solved. The reason is that Request::header(); unable to interpret the parameter with underscore(csrf_token). So after I changed to
$http.defaults.headers.common['csrfToken'] = CSRF_TOKEN;
and it works!
Thanks to rvs1977 from (https://github.com/laravel/framework/issues/1655#issuecomment-20595277)