laravel如何为所有json响应添加前缀以防止json注入 [英] laravel how to prefix all json responses to protect against json injection

查看:178
本文介绍了laravel如何为所有json响应添加前缀以防止json注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已请求此主题 Laravel-如何前缀所有json响应防止json注入

没有任何回复,所以我再试一次.

without any reply so I try again.

我尝试过

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');

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

但是它不起作用,我的意思是我一直都有标准的json格式.

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

推荐答案

如果要在响应前添加/添加数据,则可以使用响应对象getContent()方法访问响应数据.

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

然后您可以使用after属性将此内容附加到路由.

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

或者,如果您不想将过滤器附加到每条路线,那么也可以利用App::after钩子

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

这篇关于laravel如何为所有json响应添加前缀以防止json注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆