I have the following Symfony Controller:
namespace AppBundle\Controller
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
class MyController extends Controller
{
/**
* @Route("/form", name="get_form")
* @Method("GET")
*/
public function getFormAction(Request $request)
{
return $this->render('some_twig.html.twig');
}
/**
* @Route("/form_submit", name="submit_form")
* @Method("POST")
*/
public function ajaxFormAction(Request $request)
{
if($request->isXmlHttpRequest()){
return new JsonResponse(['data':"All midori"],JsonResponse::HTTP_OK);
} else {
return new JsonResponse(['data':"Echi, hentai, baka"],JsonResponse::HTTP_BAD_REQUEST);
}
}
}
The form is submitted via the following javascript code:
$("#someform").on('submit',function(e){
e.preventDefault();
var self=this; //To avoid Confusion using this
var url=$(self).attr('action');
$.ajax({
'method': "POST",
'url': url,
'data': $(self).serialize(),
'statusCode': {
400: function(data,textStatus,jqXHR) {
//Handle Error 400
},
500: function(data,textStatus,jqXHR){
//Handle error 500
}
},
'success':function(data){
//DO some stuff
}
});
})
But I have some trouble on how I can protect the Symfony Ajax method from CSRF attacks. When I try to protect via putting CSRF token to form when an aeero occurs eg. an exception thrown it renders my form junk.
Also leaving unprotected is not the best viable option. So how effectively can protect it?