laravel how to prefix all json responses to protect against json injection

夙愿已清 提交于 2019-12-11 09:35:15

问题


This topic has been request Laravel - how to Prefix all json responses to protect against json injection

without any reply so I try again.

I've tried with

Route::filter('protectionJson',function($route,$request ,$response)
{
    if($request->ajax() && ($response instanceof \Illuminate\Http\JsonResponse)){
       return ")]}',\n".json_encode($response->getData());
    }
});
Route::get('user', array('as' => 'base.user.index', 'uses' => 'App\Controllers\UserController@index'))->before('hasAccess:users')->after('protectionJson');

and

App::after(function($request, $response)
{
    if($request->ajax() && ($response instanceof \Illuminate\Http\JsonResponse)){
       return ")]}',\n".json_encode($response->getData());
    }
});

but it doesn't work I mean I've got always the standar json format.


回答1:


If you want to prepend/append data to the response you can access the response data using the response objects getContent() method.

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 this 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);
}));

Alternatively, if you don't want to attach a filter to each route, then it is also possible to utilize the App::after hook

App::after(function($request, $response)
{
    if($response instanceof \Illuminate\Http\JsonResponse) {
        $json = ")]}',\n" . $response->getContent();
        return $response->setContent($json);
    }
});


来源:https://stackoverflow.com/questions/24538305/laravel-how-to-prefix-all-json-responses-to-protect-against-json-injection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!