Cross-site request forgery (CSRF), also known as one-click attack or session riding, is a type of malicious exploit of a website where unauthorized commands are submitted from a trusted website user.
Laravel makes it easy to protect your application from CSRF attacks by inspecting every incoming POST, PUT, PATCH, or DELETE for a secret session value that a malicious request is unable to access.
Laravel automatically generates a CSRF token for each active user session. Everytime the user uses the application, a session with a new CSRF token is generated making it difficult for malicious activity.
The current session’s CSRF token can be accessed via the request’s session or via the csrf_token helper function.
use Illuminate\Http\Request;
Route::get('/token', function (Request $request) {
$token = $request->session()->token();
$token = csrf_token();
// ...
});
Anytime you define a “POST”, “PUT”, “PATCH”, or “DELETE” HTML form in your application, you should include a hidden CSRF _token field in the form so that the CSRF protection middleware can validate the request. For convenience, use the @csrf
Blade directive to generate the hidden token input field:
<form method="POST" action="/profile">
@csrf
<!-- Equivalent to... -->
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
</form>
The App\Http\Middleware\VerifyCsrfToken middleware will automatically verify that the token in the request input matches the token stored in the session. When these two tokens match, we know that the authenticated user is the one initiating the request.
In cases where using API’s, some URI’s should be excluded from CSRF protection, it is recommended to place these routes outside the web middleware group that the App\Providers\RouteServiceProvider
applies to all routes in the routes/web.php
file. You will need to exclude the routes by adding their URIs to the $except
property of the VerifyCsrfToken
middleware as follow:
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'http://example.com/foo/bar',
'http://example.com/foo/*',
];
}