Ошибка 419 page expired laravel

Before reading below make sure you have @csrf or {{ csrf_field() }} in your form
like

<form method="post">
@csrf <!-- {{ csrf_field() }} -->
... rest of form ...
</form>

The Session Expired or 419 Page Expired error message in Laravel comes up because somewhere your csrf token verification fails which means the App\Http\Middleware\VerifyCsrfToken::class middleware is already turned on. In the form the @csrf blade directive is already added, which should be fine as well.

Then the other area to check is the session. The csrf token verification is directly involved with your session, So you might want to check whether your session driver is working or not, such as an incorrectly configured Redis might cause an issue.

Maybe you can try switching your session driver/software from your .env file, the supported drivers are given below

Supported Session drivers in Laravel 5, Laravel 6 and Laravel 7 (Doc Link)

  • file — sessions are stored in storage/framework/sessions.
  • cookie — sessions are stored in secure, encrypted cookies.
  • database — sessions are stored in a relational database.
  • memcached / redis — sessions are stored in one of these fast, cache based stores.
  • array — sessions are stored in a PHP array and will not be persisted.

If your form works after switching the session driver, then something wrong is with that particular driver, try to fix the error from there.

Possible error-prone scenarios

  • Probably file-based sessions might not work because of the permission issues with the /storage directory (a quick googling will fetch you the solution), also remember putting 777 for the directory is never the solution.

  • In the case of the database driver, your DB connection might be wrong, or the sessions table might not exist or wrongly configured (the wrong configuration part was confirmed to be an issue as per the comment by @Junaid Qadir).

  • redis/memcached configuration is wrong or is being manipulated by some other piece of code in the system at the same time.

It might be a good idea to execute php artisan key:generate and generate a new app key which will, in turn, flush the session data.

Clear Browser Cache HARD, I found Chrome and Firefox being a culprit more than I can remember.

Read more about why application keys are important

If you are working with a form like login, registration, etc, and submitting it to the Laravel app using Ajax and Postman API. and you have not added csrf token in it then you will get errors as follows, 419 page expired laravel ajax, laravel 419 page expired postman, 419 page expired laravel login, Laravel 419 page expired redirect to login, Laravel 419 page expired CSRF , et cetera.

So, Through this tutorial, you will learn how to fix laravel 419 pages expired error in laravel 10, 9, 8 versions.

How to Fix 419 Page Expired in Laravel 10, 9, 8

419 Page Expired error in Laravel 10, 9, 8 using ajax post request, Postman with apis, and login & registration, etc form submit. To resolve this error, you have the following options:

  • Solution 1 – 419 Page Expired Laravel Post Login, Registration, etc Form
  • Solution 2 – 419 Page Expired Laravel Ajax
  • Solution 3 – 419 Page Expired Laravel Postman Apis
  • Solution 4 – Remove CSRF protection on specific URL

Solution 1 – 419 Page Expired Laravel Post Login, Registration, etc Form

In this first solution, To fix 419 page expired error in Laravel, you need to add @csrf with your laravel login, registration, etc forms.

So, open your login or registration blade view file and add the following line of code into your blade view file head section:

<form method="POST" action="/profile">
    @csrf <!-- add csrf field on your form -->
    ...
</form>

Solution 2 – 419 Page Expired Laravel Ajax

To fix/solve 419 page expired laravel ajax, Make sure you include the CSRF token in your Ajax request headers or data in laravel project. The CSRF token is typically stored in a meta tag within your HTML template. If you do not include it, and you are getting 419 page expired laravel or laravel csrf token mismatch ajax. Here’s an example of how to include the CSRF token in your Ajax request headers using jQuery:

So, open your blade view file and add the following line of code into your blade view file head section:

<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>

Now, you can see the following how to send csrf token with your form data using ajax in laravel:

$.ajax({
    type: "POST",
    url: '/your_url',
    data: { somefield: "Some field value", _token: '{{csrf_token()}}' },
    success: function (data) {
       console.log(data);
    },
    error: function (data, textStatus, errorThrown) {
        console.log(data);

    },
});

OR

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

Solution 3 – 419 Page Expired Laravel Postman Apis

When encountering a “419 Page Expired” error in Laravel while using Postman, it typically indicates an issue with CSRF (Cross-Site Request Forgery) protection. Laravel’s default CSRF protection requires a valid CSRF token to be included with each POST request. To resolve this error, you need to follow the following steps:

If you prefer to keep CSRF protection enabled, you need to include the CSRF token with your POST requests in Postman. Here’s how:

  1. Send a GET request to the endpoint you’re testing in Postman. Make sure it’s a route that requires authentication.
  2. Inspect the response headers for the Set-Cookie header. It should contain a cookie named XSRF-TOKEN with the CSRF token value.
  3. Copy the value of the XSRF-TOKEN cookie.
  4. In Postman, go to the Headers tab for your POST request.
  5. Add a new header with the key X-XSRF-TOKEN and paste the CSRF token value as the header value.
  6. Send the POST request again, and the “419 Page Expired” error should be resolved.

Solution 4 – Remove CSRF protection on specific URL

To disable CSRF protection field for all routes group or specific routes in laravel. So, visit app\Http\Middleware\ directory and open VerifyCsrfToken.php file. Then add the following lines of code in it:

<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
  protected $except = [
    'payment/*', // routes group
    'specific-route', // specific route
  ];
}

Conclusion

That’s all; Through this tutorial, you have learned how to fix laravel 419 page expired error in laravel 10, 9, 8, 7 versions.

Recommended Laravel Tutorials

This is a very common issue when you got the 419 page expired issue in the Laravel application. This happens due to inactivity on the page for a long time. Laravel handles the form request with a CSRF (Cross-Site Request Forgery) token. For every form submit, Laravel generates a new token. This is a secure way to handle the form. Through this token, Laravel detects the form request. If it is coming from outside of the application then it prevents the request. But, this form request detection using CSRF token is checked only on the web applications. If you are creating a REST API in Laravel then that CSRF token won’t work. That’s why we use JWT, Passport, or Sanctum API authentication package.

Today, in this post, we will see how you can resolve this 419 page expired issue. We will see the different routes with parameters or without parameters in POST requests. Let’s have a quick look through a demo application.

Laravel 419 Page Expired
Laravel 8 Page Expired

Prerequisites

I am assuming, you already have the Laravel application set up. If not then you will require the below configurations for creating a new application.

  • PHP >= 7.3
  • MySQL (version > 5)
  • Apache/Nginx Server
  • VS Code Editor
  • Composer

I already have the Laravel 8 application setup. Hence, I am not going to create a new application for now. I will be using that one.

Create a Form in Laravel For Resolving 419 Page Expired Issue

Here, you will require at least a controller and a view. I am not going to store any data in the database. Instead, I will just submit the form and check the response. Here, I will be submitting the form without the CSRF token.

So, firstly, create a view in the resources folder and add the below form snippet. I have created a view with the name create.blade.php.

<!doctype html>
<html lang="en">
<head>
    <title> Create Post - CKEditor 4 Example </title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
    <div class="container mt-5">
        <form action="{{ route('posts.store') }}" method="POST">
            <div class="row">
                <div class="col-xl-8 col-lg-8 col-sm-12 col-12 m-auto">
                    <div class="card shadow">
                        <div class="card-header">
                            <h4 class="card-title font-weight-bold"> Laravel Form Handling Without CSRF Token </h4>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label> Title </label>
                                <input type="text" class="form-control" name="title" placeholder="Enter the Title">
                            </div>
                            <div class="form-group">
                                <label> Body </label>
                                <textarea class="form-control" id="description" placeholder="Enter the Description"
                                    name="description"></textarea>
                            </div>
                        </div>
                        <div class="card-footer">
                            <button type="submit" class="btn btn-success"> Save </button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</body>
</html>

In the above form, I haven’t added the CSRF token. So, when this form will be submitted, it will throw the 419 page expired error.

How to Implement Sweet Alert in Laravel 8 For Dialog Alert

However, before submitting the form, we will require a controller to handle the form request. Hence, create a controller.

Create a Controller For Form Handling without CSRF token

You will require a controller in which you will handle the form request. Therefore, come back to the terminal and hit the below command.

php artisan make controller:HomeController

After creating the controller, let’s add the below code.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
    public function index() {
        return view('create');
    }
    public function store(Request $request) {
        return $request->all();
    }
}

Respectively, add the routes for running your application.

Add Routes in Laravel 8

Open the web.php file and add the below routes.

<?php
use App\Http\Controllers\HomeController;
use Illuminate\Support\Facades\Route;
Route::get('posts', [HomeController::class, 'index'])->name('posts');
Route::post('posts', [HomeController::class, 'store'])->name('posts.store');

Now, run your application and navigate to the above route.

Form without CSRF Token in Laravel
Form without CSRF Token in Laravel

When you will submit this form, you will get the 419 page expired error.

419 Page Expired - Without CSRF Token
419 Page Expired – Without CSRF Token

Now, to resolve this issue, you have to exclude the POST request route.

Exclude Route From Verify CSRF Token in Laravel

Navigate to the app/Http/Middleware folder in your Laravel application. You will have the VerifyCsrfToken.php. When you will click on that, it will look like shown below.

VerifyCsrfToken.php
VerifyCsrfToken.php

Currently, the except array is empty. So, you have to pass the route here in the array for which you don’t want CSRF token on the form submit. So, as per the routes, we have the route named posts for submitting the form defined in the POST method.

Hence, you have to enter the route name in the array as shown below.

<?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<int, string>
     */
    protected $except = [
        'posts'
    ];
}

Check Result of 419 Page Expired Issue

Now, try to submit the form by filling up the details.

Submit Form Without CSRF Token
Submit Form Without CSRF Token

After submitting the form, you will get the form data. You can see this in the below result.

Form Submitted Without CSRF Token
Form Submitted Without CSRF Token

This was a simple route with no parameters. However, sometimes you will have a route with parameters defined in the POST method. You will not have the exact name of that parameter because that will be a dynamic value every time. So, let’s see how to handle that type of route without CSRF Token.

Exclude Parameterized Route From CSRF Token

Let’s modify the form action in the view. Here, I added a token in the form action.

 @php $token = md5(now()); @endphp
 <form action="{{ url('posts', $token) }}" method="POST">

This will generate a token and now, we have the form action with a parameter. But, the form method is POST. Let me show you how this will look. I opened the developer console in the browser and under the elements tab, I have the form action like this.

Form Action with Token
Form Action with Parameter
<!doctype html>
<html lang="en">
<head>
    <title> Laravel Page Expired Issue </title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
    <div class="container mt-5">
        @php $token = md5(now()) @endphp
        <form action="{{ url('posts', $token) }}" method="POST">
            <div class="row">
                <div class="col-xl-8 col-lg-8 col-sm-12 col-12 m-auto">
                    <div class="card shadow">
                        <div class="card-header">
                            <h4 class="card-title font-weight-bold"> Laravel Form Handling Without CSRF Token </h4>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label> Title </label>
                                <input type="text" class="form-control" name="title" placeholder="Enter the Title">
                            </div>
                            <div class="form-group">
                                <label> Body </label>
                                <textarea class="form-control" id="description" placeholder="Enter the Description"
                                    name="description"></textarea>
                            </div>
                        </div>
                        <div class="card-footer">
                            <button type="submit" class="btn btn-success"> Save </button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</body>
</html>

Now, add one more route below those routes.

Route::post('posts/{token}', [HomeController::class, 'store']);

Let’s try to submit the form again. In the below result, you can see we have the same result of 419 page expired.

419 Page expired issue
Form Submit Result with Parameterized Route

Now, let’s exclude this route from verifying CSRF token. Therefore, come back to the same file (VerifyCsrfToken.php) and add the parameterized route as shown below.

<?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<int, string>
     */
    protected $except = [
        'posts',
        'posts/*'
    ];
}

In the above array, I have passed 'posts/*' it means whatever parameter will be after posts, it will exclude it from verifying the token.

Now, check the result by submitting the form.

Parameterized Route without CSRF Token
Parameterized Route without CSRF Token

The result is shown below, you can see the form has been submitted successfully without any token issue.

Fixed 419 page expired issue in laravel
Parameterized Route – Form Submitted Without Token Issue

Similarly, if you have the token before the endpoint then you can pass the ‘*’ before the endpoint. You can have more than one parameter in the form action. You can exclude them in the same way.

Conclusion

We got to know how to resolve the 419 page expired issue in Laravel. We excluded the routes from verifying a CSRF token. You can exclude the parameterized route and non-parameterized route as well. But, it is not recommended in the web application to exclude the route. Generally, the middleware checks the requests if it is coming from outside the application then it asks for a CSRF token. I hope you will find helpful to this post.

The 419 Page Expired error is very common and easy to fix in Laravel applications. It’s caused by the internal framework mechanism called CSRF protection. CSRF stands for Cross-Site Request Forgery and is one of the most popular attacks.

An error page layout may differ between the framework versions, but the error code (419) and the error message (Page Expired) are the same. The following screenshot comes from Laravel 8.

To avoid this issue, every POST, PUT, PATCH, and DELETE request have to have a csrf token as a parameter. Depending on the way you send your request, you have several options to append this parameter.

Solution #1 – Blade directive

When you create a form in a Blade template, the solution is extremely simple. Blade template engine has a built-in directive @csrf that generates a hidden HTML input containing the token. The directive should be added just after opening <form> tag.

<form method="POST" action="/register">
    @csrf
        
    <label for="email">Email</label>
    <input type="email" name="email">

    <label for="email">Password</label>
    <input type="password" name="password">

    <button type="submit">Save</button>
</form>

Alternatively, you can create a token input manually, using csrf_token() method. Outcome will be identical.

<!-- Equivalent for @csrf directive -->
<input type="hidden" name="_token" value="{{ csrf_token() }}">

Solution #2 – Header of the Ajax request

As for Ajax request, the solution is a little different, but also quite simple. All you have to do is to add the csrf token to the head section of your HTML document and send it as an X-CSRF-TOKEN header with your request.

<head>
    <meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
var request;
var form = $("form");
var data = {
    'email': form.find('input[name="email"]').val(),
    'password': form.find('input[name="password"]').val()
};
var headers = {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}

request = $.ajax({
    url: "/register",
    type: "post",
    headers: headers,
    data: data
});

request.done(function (){
    console.log("It works!");
});

Solution #3 – Disabling CSRF validatation for some endpoints

For some specific endpoints, you can disable CSRF validation. Specific URLs can be excluded in the $except array of the VerifyCsrfToken class. This way you can exclude either the exact URL or group of URLs with a common prefix.

// /app/Http/Middleware/VerifyCsrfToken.php

class VerifyCsrfToken extends Middleware
{
    protected $except = [
        'payment/*',  // exclude all URLs wit payment/ prefix
        'user/add' // exclude exact URL
    ];
}

Excluding from CSRF protection should be used only for endpoints that are used by external applications (like payment providers). However, it’s also convenient to use api route file when you have many endpoints like that. They would be automatically excluded from the CSRF protection.

Conclusion

CSRF protection is by default enabled for all POST, PUT, PATCH, and DELETE requests within web routes file (those in api file are excluded). That approach has many advantages and allows developers to focus on more complex issues. However, that may be also confusing for less experienced programmers because requires more knowledge about a request lifecycle. Anyway, the three solutions I presented in this post are more than enough to handle all possible use cases and easily work with CSRF tokens in Laravel applications.

Опубликовано:

  • Backend
  • Laravel

Использование CSRF-токенов добавляет дополнительный уровень безопасности, подтверждая, что запрос исходит от того же приложения, а не от вредоносного источника. Laravel обеспечивает встроенную защиту от CSRF-атак путём генерации и проверки CSRF-токенов.

Использование CSRF-токенов добавляет дополнительный уровень безопасности, подтверждая, что запрос исходит от того же приложения, а не от вредоносного источника. Laravel обеспечивает встроенную защиту от CSRF-атак путём генерации и проверки CSRF-токенов. Однако его неправильное использование может привести к ошибке: 419 Page Expired.

Чтобы устранить ошибку 419 Page Expired, необходимо убедиться, что CSRF-токен включён в отправляемую форму, добавив @csrf после между открывающим и закрывающим тегами <form>. При этом в форму будет автоматически добавлено скрытое поле input, содержащее CSRF-токен.

Вот пример того, как будет выглядеть обновлённая форма с использованием @csrf:

<form method="POST" action="/your-route">
@csrf
<!-- Остальные элементы формы -->
</form>

В качестве альтернативы вы можете использовать csrf_field() в <form>, которая выглядит следующим образом:

<form method="POST" action="/your-route">
{{ csrf_field() }}
<!-- Остальные элементы вашей формы -->
</form>

Обратите внимание, что ошибка 419 Page Expired может возникнуть и при наличии токена. Обычно это означает, что пользователь был неактивен в течение определённого времени и срок действия токена истёк. Это можно исправить, просто обновив страницу и отправив форму заново.

В примерах кода выше мы узнали, как применить токен к обычной форме. Читайте дальше, чтобы узнать, как добавить CSRF-токен в запросы Ajax POST с помощью jQuery или Axios. Мы также узнаем, как отключить проверку CSRF-токена для определённого маршрута или всего приложения. Наконец, мы ответим на некоторые часто задаваемые вопросы о том, почему GET-запрос не требует CSRF верификации и почему API вообще не требуют её.

Как исправить 419 (unknown status) с помощью Ajax POST (jQuery)

При отправке формы с помощью AJAX из jQuery вы можете получить ответ об ошибке — 419 (unknown status).

Используя Laravel/jQuery, вы можете исправить ошибку 419 (unknown status), добавив вызов csrf_token() в раздел <head> и вызвав $.ajaxSetup, для настройки jQuery на добавление токена в заголовки всех последующих POST-запросов.

Выполните следующие шаги, чтобы применить это исправление к вашему коду:

  1. Добавьте CSRF-токен в раздел <head>:

    <head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    </head>
  2. Добавьте вызов $.ajaxSetup:

    <script>
    $.ajaxSetup({
    headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
    });
    </script>
  3. Добавьте код jQuery для отправки POST-запроса:

    <script>
    // Отправляем сокращенный jQuery POST:
    $.post('/formProcessor');

    // Или отправьте обычный jQuery POST:
    $.ajax({
    type: "POST",
    url: "/formProcessor"
    });
    </script>

Полный пример (маршрут и вид):

routes/web.php:

Route::get('/form', function () {
return view('form');
});

Route::post('/formProcessor', function () {
return response('', 200);
});

/resources/views/form-jquery-ajax.blade.php:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery Ajax POST Example</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
</head>
<body>
<button class="sendButton">Click me</button>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.sendButton').click(function(){
$.post('/formProcessor');
});
</script>
</body>
</html>

Использование Axios для отправки Ajax POST (нет необходимости устанавливать CSRF-токен)

Axios — это HTTP-клиент для JavaScript. Он значительно упрощает отправку AJAX POST-запросов. Он делает это, устраняя необходимость включать jQuery, устанавливать токен или вызывать функцию настройки. Я рекомендую использовать Axios в любом проекте, который отправляет Ajax-запросы из JavaScript.

По умолчанию Laravel поставляется с Axios и Vite. Для того чтобы использовать Axios, нам просто нужно выполнить следующие команды:

npm install
npm run build

Эти команды установили Axios и создали правильный .js файл в папке /public.

Теперь вы можете включить app.js и использовать Axios в своём коде для отправки POST-запроса, как показано в этом примере:

/resources/views/form-axios-ajax.blade.php:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery Ajax POST Example</title>
@vite(['resources/js/app.js'])
</head>
<body>
<button class="sendButton">Click me</button>
<script>
document.querySelector('.sendButton').addEventListener('click', function (event) {
axios.post('/formProcessor', {
// Полезная нагрузка запроса
data: 'your-data'
}).then(response => {
// Обработка ответа
alert('successful!');
}).catch(error => {
// Обработка ошибки
console.error(error);
});
});
</script>
</body>
</html>

Как отключить проверку CSRF-токенов в Laravel

Чтобы отключить проверку токена CSRF для всех маршрутов в Laravel, вы можете удалить промежуточное программное обеспечение CSRF, выполнив следующие шаги:

  1. Откройте файл app/Http/Kernel.php в вашем проекте Laravel.

  2. Найдите свойство $middleware в классе Kernel.

  3. Найдите middleware класс VerifyCsrfToken, который обычно указывается как \App\Http\Middleware\VerifyCsrfToken::class.

  4. Удалите или закомментируйте строку, содержащую middleware класс VerifyCsrfToken.

    Например, измените:

    app/Http/Kernel.php:

    \App\Http\Middleware\VerifyCsrfToken::class,

    на

    // \App\Http\Middleware\VerifyCsrfToken::class,
  5. Сохраните изменения в файле Kernel.php.

Удалив middleware VerifyCsrfToken, проверка маркера CSRF будет отключена для всех маршрутов в вашем приложении Laravel. Однако помните, что этот подход устраняет важную меру безопасности, поэтому используйте его с осторожностью и только в конкретных случаях, когда защита CSRF не требуется.

Как отключить CSRF-токен только для определённого маршрута

Чтобы отключить проверку CSRF-токена для определённого маршрута в Laravel, вы можете исключить маршрут из защиты CSRF, изменив middleware CSRF. Вот как это можно сделать:

  1. Откройте файл app/Http/Middleware/VerifyCsrfToken.php в вашем проекте Laravel.

  2. В классе VerifyCsrfToken найдите свойство except. Это свойство определяет URI, которые должны быть исключены из проверки CSRF-токенов.

  3. Добавьте URI маршрута, который вы хотите исключить из защиты CSRF, в массив except. Например, если вы хотите исключить маршрут /example из проверки CSRF, добавьте следующую строку в массив except:

    app/Http/Middleware/VerifyCsrfToken.php:

    protected $except = [
    '/example',
    ];

    Если вам нужно исключить несколько маршрутов, вы можете добавить их в массив через запятую.

  4. Сохраните изменения в файле VerifyCsrfToken.php.

Существуют обоснованные случаи использования отключения VerifyCsrfToken для определённых маршрутов. Например, чтобы наше приложение могло получать обратные вызовы от сторонних систем, например, от поставщика платежей. Обычно это используется для обновления статуса заказа до оплаченного.

Добавив конкретный маршрут в массив except в middleware VerifyCsrfToken, Laravel обойдёт проверку CSRF-токена для этого маршрута. Важно отметить, что хотя этот подход может быть полезен в определённых сценариях, отключение CSRF защиты должно выполняться осторожно и только в случае необходимости для обеспечения безопасности вашего приложения.

Почему маршруты API Laravel не используют проверку CSRF-токена

Стоит отметить, что в Laravel middleware для проверки CSRF-токенов намеренно не добавляется автоматически в маршруты API.

Маршруты API Laravel не используют проверку CSRF (Cross-Site Request Forgery) по умолчанию из-за своей stateless природы. API обычно работают в режиме stateless, то есть они не хранят данные сессии и не поддерживают состояние клиента между запросами.

Вместо этого API используют механизмы аутентификации на основе токенов, такие, как JWT (JSON Web Tokens) или OAuth для аутентификации и авторизации запросов. Такая аутентификация на основе токенов обеспечивает безопасный механизм без необходимости использования CSRF-токенов. Однако для традиционных веб-форм защита от CSRF остаётся крайне важной.

Почему к GET-запросам Laravel не применяется проверка CSRF-токена

CSRF-токен требуется в любых запросах POST, PUT, PATCH или DELETE, которые отправляются с веб-сайта. Но почему он не требуется, когда мы отправляем GET-запрос?

GET-запросы обычно используются для получения данных и считаются безопасными, поскольку они не должны изменять данные на стороне сервера. Поскольку CSRF атаки основаны на несанкционированных модификациях, применение CSRF-токенов к GET-запросам не требуется.

Для полноты картины стоит упомянуть, что запросы OPTIONS и HEAD также считаются запросами только для чтения, которые, как и GET-запросы, не требуют проверки CSRF-токена. Как показывает официальный код VerifyCsrfToken Middleware:

VerifyCsrfToken.php:

protected function isReading($request)
{
return in_array($request->method(), ['HEAD', 'GET', 'OPTIONS']);
}

Заключение

В этой статье рассматривалось, как устранить ошибки 419 Page Expired и CSRF token mismatch в Laravel при использовании обычных форм или Ajax-запросов POST, отправленных с помощью jQuery или Axios.

Кроме того, в статье было показано, как можно отключить проверку CSRF-токена для определённого маршрута и как её можно отключить полностью. Наконец, мы также объяснили, почему маршруты API не используют проверку CSRF-токена по умолчанию и почему GET-запросы в Laravel не проверяют токен CSRF.

Надеюсь, эта статья будет вам полезна. Счастливого кодинга!

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Ошибка 420 уаз хантер
  • Ошибка 4191 бмв е46
  • Ошибка 419 эпос
  • Ошибка 420 уаз буханка
  • Ошибка 419 что это

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии