Google News
logo
Laravel - Interview Questions
What is CSRF protection and CSRF token?
First let's understand CSRF - It's cross-site request forgery attack. Cross-site forgeries are a type of malicious exploit where unauthorized commands can be executed on behalf of the authenticated user. Laravel generates a CSRF "token" automatically for each active user session. This token is used to verify that the authenticated user is the one actually making the requests to the application.
<form method="POST" action="/profile">
   @csrf
   ...
</form>
If you're defining an HTML form in your application you should include a hidden CSRF token field in the form so that middleware (CSRF Protection middleware) can validate the request. VerifyCsrfToken middleware is included in web middleware group. @csrf blade directive can be used to generate the token field.
 
If using JS driven application then you can attach your js HTTP library automatically attach the CSRF token with every HTTP request. resources/js/bootstrap.js is the default file which registers value of csrf-token meta tag with HTTP library.
 
To remove URIs from CSRF in verifyCsrfToken we can use $except property where can provide URLs which we want to exclude.
Advertisement