[英]Token mismatch with ajax post request to a subdomain
我正在使用Laravel框架开发Web应用程序。
当我从app.com向api.app.com发送ajax请求并传递在app.com上生成的csrf令牌时,我总是会收到TokenMismatchException。
问题在于对api.app.com的ajax请求正在那里创建一个新会话。 我正在为app.com和api.app.com使用单个laravel安装。
子域路由:
Route::group(array('domain' => 'api.app.com'), function()
{
Route::controller('user', 'MyApp\API\UserController');
});
CSRF筛选器仅适用于POST请求:
Route::when('*', 'csrf', ['post']);
CSRF过滤器:
Route::filter('csrf', function()
{
$token = Input::get('_token');
if (Session::token() != $token)
{
throw new Illuminate\Session\TokenMismatchException;
}
});
我的ajax请求看起来像这样:
$.ajax({
'url': '//api.app.com/user/hello',
'data': {
fields:'',
'_token': 'output of csrf_token() from app.com'
},
'dataType': 'json',
'type': 'POST'
}).done(done).fail(fail).always(always);
如果我不使用api的子域,则一切正常。 我正在使用memcached作为会话存储。
编辑:我的会话域设置为.app.com。
'domain' => '.app.com',
我通过发送Access-Control-Allow-Credentials: true
标头并将我的ajax请求函数更改为此来解决了这个问题:
$.ajax({
'url': '//api.app.com/user/hello',
'data': {
fields:'',
'_token': 'output of csrf_token() from app.com'
},
'dataType': 'json',
'type': 'POST',
xhrFields: {
withCredentials: true
}
}).done(done).fail(fail).always(always);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.