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

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

问题描述

我正在编写一个使用 Laravel 4.1 构建的 api 的 angularjs 应用程序.我希望防止 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 内置的一种解决此问题的方法是在所有服务器 json 响应前添加以下字符串 ")]}',\n".

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.

每当我的控制器返回一个 json Response 对象时,有没有办法在这个字符串前加上前缀?

Is there a way to prefix this string whenever my controller returns a json Response object?

return Response::json($prefix.$json, 200);

推荐答案

如果您想在响应中添加/附加数​​据,您可以使用过滤器.

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

然后您可以使用 after 属性将过滤器附加到路由.

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 的路由附加过滤器,那么也可以使用 App::after 钩子.

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 - 如何为所有 json 响应添加前缀以防止 json 注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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