I'm trying to make ajax (using jquery) post to some of my controller methods. How can I generate a valid csrf and send it along with the data.
Note. I'm not submitting a form, I can use twig_fuel_extension's form_open() to automatically generate the csrf input field. I need to send image from summernote's editor to an endpoint on the server so that the image can be uploaded instead of it being represented as base64 which is summernote's default.
I already have a working code, but when I turn on csrf settings to secure the app, it rejects my ajax posts due to missing csrf.
The CSRF token is set in a cookie when you generate one.
See Security::js_fetch_token() for the javascript code needed to fetch the token from the cookie and add it to the posted data. Make sure you use the correct (= configured) variable so it can be checked by your code.
Only do this when the post data is submitted, as other forms that may be open simultaneously might use the token on submission, causing a new token to be generated.
If I enable these options inside config.php the ajax call return page not found 404 which is the same error fuelphp gave me when I tried submitting a form without csrf token field.
That config would throw a HttpBadRequestException when the validation failed, which you should be able to find back in the application log files.
You might want to debug Security::check_token(), and see if static::$csrf_token_key contains "fuel_csrf_token", and if the value fetched there is the value you posted. Also check if static::$csrf_token contains that value.
You need to do that before the code in the method, to make sure nothing alters the data (the call to fetch_token for example will generate a new token).
You might also want to add an exception handler for that exception, so you can pass a meaningful message back if it happens on a json call.
Thanks. I'm yet to try it as I'm very busy with other stuffs. I'll let you know when I try it.
Just a quick question.
I'm using controller template, the template file gets a bunch of variables passed to it, how can i get the values of those variables from the inner template.
What I mean is this template.twig calls {{ site.name }} to get the name of the website that was passed to it. How can I access this from all other child template which uses the template.twig?