2014-01-29 32 views
4

我正在寫一個angularjs應用程序,它正在使用Laravel 4.1構建的api。我正在尋找防止json注射。Laravel - 如何前綴所有JSON響應,以防止JSON注入

構建到angularjs中的一個方法可以解決這個問題,即將所有服務器json響應前綴爲以下字符串")]}',\n"

angularjs $ http服務將自動從所有json響應中剝離此字符串。

我不希望手動附加這個字符串到我的api服務的每個json響應。

當我的控制器返回一個json響應對象時,是否有一種方法可以將此字符串作爲前綴?

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

+1

你設法溶膠這是嗎?我也在尋找解決方案.. @gravy – Oguzhan

+0

http://stackoverflow.com/questions/24538305/laravel-how-to-prefix-all-json-responses-to-protect-against-json-injection/24545383 – Whisher

+0

最後,一個答案!我會放棄它。謝謝! – Gravy

回答

-2

這應該工作:

//in app/filters.php 
App::after(function($request, $response) 
{ 
    if($request->ajax()) $response = ")]}',\n".$response; 
}); 
3

如果要在前面加上/追加數據,你可以使用過濾器的響應。

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

然後,您可以使用after屬性將過濾器附加到路線。

Route::get('/test', array('after' =>'json.protect', function() 
{ 
    $test = array(
     "foo" => "bar", 
     "bar" => "foo", 
    ); 

    return Response::json($test); 
})); 

另外,如果你不想過濾器連接到輸出JSON每個路由,那麼它也可以利用App::after鉤。

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

我知道這個問題被問得很久以前,而是要幫助誰需要這種方法與Laravel 5和AngularJS這可以通過創建一個Response Macro,所以在你ResponseMacroServiceProvider類你定義boot方法來實現像:

public function boot() 
{ 
    Response::macro('angular', function($value, $status = 200) 
    { 
     $response = Response::make($value, $status); 

     $json = ")]}',\n" . $response->getContent(); 

     return $response->setContent($json); 
    }); 
} 

然後,只需打電話給你的控制器內的response()輔助函數:

return response()->angular(['item' => 'value']);