Cross Site Request Forgery (CSRF) is a mechanism to protect website from POST requests not originating from the original website.
For example, you have a website named xyz.com and you have a URL /create-user that accepts user data via POST request. Now, if someone create a form on their website something like this:
<form method="post" action="http://xyz.com/create-user"> ... </form>
In this case, we will be getting data from some other website. That website may have skipped form validation, put malicious script or anything else that can be dangerous to our site.
To protect this, CSRF tokens are added on the website that is generated by the original website itself. When form is submitted, this token is sent back to original website. The code then checks if token is valid, i.e. the form is submitted on the original website only.
In Laravel, we can create this token like this:
<input type="hidden" name="_token" value="<?php echo csrf_token();?>"/>
CSRF is a good thing, but it can cause problems if you are submitting your form through a mobile app of your own website.
Our POST requests will be denied from mobile app because we are not sending any CSRF token to the server.
What we can do is to tell Laravel not to check CSRF for certain URLs. This can be done as follows:
Create your URLs for mobile apps like this:
Now open the file: app/Http/Middleware/VerifyCsrfToken.php
Modify the $except array like this:
protected $except = [ 'api/*', ];
That’s it, we are done.