Laravel - 如何preFIX所有JSON响应,以防止注射JSON [英] Laravel - how to Prefix all json responses to protect against json injection
问题描述
我写的angularjs应用程序,它消耗与Laravel 4.1内置的API。我期待,以防止注射的JSON
I am writing an angularjs app which is consuming an api built with Laravel 4.1. I am looking to protect against json injection.
建成angularjs解决这个问题的方法之一是preFIX与以下字符串)]}',\\ n
所有服务器JSON响应。
One method built into angularjs to fix this is to prefix all server json responses with the following string ")]}',\n"
.
该angularjs $ HTTP服务会自动从所有JSON响应脱衣此字符串。
The angularjs $http service will automatically strip this string from all json responses.
我不希望有手动附加这个字符串到我的API为每一位JSON响应。
I don't want to have to attach this string manually to every json response which my api serves.
有没有办法来preFIX这串每当我的控制器返回一个JSON Response对象?
Is there a way to prefix this string whenever my controller returns a json Response object?
返回响应:: JSON($preFIX $ JSON,200);
推荐答案
如果您想prePEND /将数据添加到您可以使用过滤器的响应。
If you want to prepend/append data to the response you can use filters.
Route::filter('json.protect',function($route,$request,$response = null)
{
if($response instanceof \Illuminate\Http\JsonResponse) {
$json = ")]}',\n" . $response->getContent();
return $response->setContent($json);
}
});
您可以然后使用在
属性过滤器附加到路径。
You can then attach the filter to the route using the after
property.
Route::get('/test', array('after' =>'json.protect', function()
{
$test = array(
"foo" => "bar",
"bar" => "foo",
);
return Response::json($test);
}));
另外,如果你不想过滤器附加到输出JSON每个路由,那么它也有可能挂钩后,利用应用::
Alternatively, if you don't want to attach a filter to each route that outputs json, then it is also possible to utilise the App::after
hook.
App::after(function($request, $response)
{
if($response instanceof \Illuminate\Http\JsonResponse) {
$json = ")]}',\n" . $response->getContent();
return $response->setContent($json);
}
});
这篇关于Laravel - 如何preFIX所有JSON响应,以防止注射JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!