How to disable CSRF LARAVEL verification

Laravel CSRF protection explained w/example: learn how to disable & configure CSRF protection in Laravel apps.

Disabling CSRF Protection in Laravel

Laravel provides CSRF protection to protect your application from cross-site request forgery (CSRF) attacks. By default, all requests to your application must be accompanied by a CSRF token, which is sent as an X-CSRF-TOKEN header. However, in some cases, you may need to disable CSRF protection. For example, if you are building an API or a single-page application (SPA) that will be accessed by multiple users, you may need to disable CSRF protection to allow users to authenticate without having to include a CSRF token in every request. In order to disable CSRF protection in Laravel, you need to add the following lines to your AppHttpMiddlewareVerifyCsrfToken file:

protected $except = [
    // Routes that should not be checked for CSRF protection
];
The $except array contains a list of routes that should not be checked for CSRF protection. You can add the routes that you want to be excluded from CSRF protection in this array. For example, if you want to disable CSRF protection for the login route, you can add the following line to the $except array:

protected $except = [
    'login',
];
Once you have added the routes to the $except array, Laravel will no longer check for CSRF protection on those routes. Note that you should only disable CSRF protection on routes that do not involve user input, such as a login route or an API endpoint. It is important to note that disabling CSRF protection can potentially open your application up to CSRF attacks, so it should not be done lightly. If you are disabling CSRF protection, make sure that you take other steps to protect your application, such as rate-limiting requests, using an API key, or using OAuth for authentication. Disabling CSRF protection can be a useful tool, but it should be used with caution. If you are unsure about whether or not you need to disable CSRF protection, it is best to leave it enabled.

Answers (0)