419 page expired что за ошибка как исправить

Отправить запрос в Laravel — Ошибка — 419 Извините, ваша сессия / 419 ваша страница истекла

419 К сожалению, срок вашего сеанса истек. Обновите страницу и попробуйте еще раз.

В версии 5.6 такой проблемы не было.

Перед чтением ниже убедитесь, что у вас есть @csrf или > в вашей форме нравится

Сообщение об ошибке Session Expired или 419 Page Expired в larvel появляется из-за того, что где-то не удается проверить ваш токен csrf, что означает, что AppHttpMiddlewareVerifyCsrfToken::class промежуточное ПО уже включено. В форме @csrf уже добавлена ​​директива blade, что тоже должно быть хорошо.

Затем другая область для проверки — это сеанс. csrf Маркер проверка непосредственно связана с вашей сессией, поэтому вы можете проверить , является ли драйвер сеанса работой или нет, например, неправильно настроенного Redis может вызвать проблемы.

Возможно, вы можете попробовать переключить драйвер / программное обеспечение сеанса из .env файла, поддерживаемые драйверы приведены ниже.

Поддерживаемые драйверы сеансов в Laravel 5, Laravel 6 и Laravel 7 (Doc Link)

  • file — сеансы хранятся в хранилище / framework / sessions.
  • cookie — сеансы хранятся в безопасных зашифрованных файлах cookie.
  • database — сеансы хранятся в реляционной базе данных.
  • memcached / redis — сеансы хранятся в одном из этих быстрых хранилищ на основе кеша.
  • array — сеансы хранятся в массиве PHP и не сохраняются.

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

Возможные сценарии, подверженные ошибкам

Вероятно, сеансы на основе файлов могут не работать из-за проблем с правами доступа к /storage каталогу (быстрый поиск в Google даст вам решение), также помните, что установка 777 для каталога никогда не является решением.

В случае с драйвером базы данных ваше соединение с БД может быть неправильным, или sessions таблица может не существовать или неправильно настроена (неправильная часть конфигурации была подтверждена как проблема в соответствии с комментарием @Junaid Qadir).

redis/memcached конфигурация неверна или одновременно обрабатывается другим фрагментом кода в системе.

Было бы неплохо выполнить php artisan key:generate и сгенерировать новый ключ приложения, который, в свою очередь, сбрасывает данные сеанса.

Очистить кеш браузера СЛОЖНО , я обнаружил, что хром и firefox виноваты больше, чем я могу вспомнить.

Laravel по-русски

Русское сообщество разработки на PHP-фреймворке Laravel.

  • Темы: Активные | Без ответов

Страницы 1

#1 09.07.2019 16:07:58

Ошибка 419 при любых настройках сессии и формы

Всем привет.
Проблема такая
У меня при отправке формы ошибка 419 page expired.
Перелопатив всё, что нашел в гугле, я пробовал делать следующее:

Проставлять права на запись в папке storage (файлы создаются при каждом обновлении страницы новые)

Переключился на хранение в БД (новые строки создаются)

Прописывал в форме так: @csrf

чистил кэши, пересобирал проект после удаления папки “vendor”

Ничего из этого не помогло. Единственным выходом было отрубить эту проверку csrf токена.
Сайт вертится на open server. Laravel 5.8 самая свежая.
Повторюсь, что всё работает, если вырубить проверку токена. МОжет надо что-то с сервером делать?
Код роута:

Что ЭТОГО 419 страница истекла laravel ОШИБКА

Если вы используете приложение, разработанное в laravel, вы можете получить сообщение об ошибке «Срок действия страницы 419 истек».

Что такое 419 Страница просрочена

Давайте сначала обсудим 419 код состояния HTTP, Код состояния 419 Указывает, что аутентификация не удалась для ранее аутентифицированного запроса или истек срок действия ключа / токена аутентификации. Если вы посмотрите на стандартные коды состояния HTTP, вы не найдете его там, вы можете каким-то образом рассматривать его как альтернативу 401, что если код статуса для неавторизованных. Таким образом, это означает, что когда вы получаете ошибку с истекшим сроком действия 419 страниц, это означает, что сервер пытается сообщить вам, что ваша аутентификация для определенного запроса истекла.

Почему вы получаете 419 Page истек в Laravel?

Laravel Framework имеет функцию безопасности, которая помогает вам в защита вашего сайта от CSRF, Если вам интересно, почему вы получаете эту ошибку, прочитайте этот пример, и вы узнаете о базовом механизме защиты от CSRF в Laravel и о причине ошибки.

Допустим, вы зашли на страницу входа в приложение laravel в своем браузере, и вам позвонил друг. Вы были заняты разговором с другом и забыли о входе в приложение, и страница оставалась там довольно долго. Вы вернулись туда, где ушли, вы заполнили форму и Voilá, ошибка 419 страницы истекла, Если вы просматриваете страницу или просматриваете исходный код в браузере и просматриваете форму входа, это скрытое поле ввода с длинной строкой, например, токен CSRF, этот токен отвечает за защиту от CSRF [подробнее о csrf]. Когда вы покинули экран своего компьютера и были заняты разговором с другом, срок действия этого токена истек, и ваш запрос был отклонен с кодом состояния 419 HTTP.

Что может вызвать проблему истечения срока действия страницы 419

  • Вы не отправляете токен CSRF с формой и не используете промежуточное ПО verifyCSRF
  • Вы тратите слишком много времени на отправку запроса
  • вы взломали скрытое поле токена
  • Вы правильно настроили параметры сеанса в файле конфигурации сеанса

Как это исправить?

Самый простой способ исправить проблему — перезагрузить страницу. После перезагрузки вы получите новый токен, который означает, что вы готовы к работе.

Проверьте токен csrf в форме, которую вы отправляете. Наконец, убедитесь, что конфигурация для домена и файлов cookie выполнена правильно в файле конфигурации сеанса.

Если вы разрабатываете приложение, вы можете время от времени использовать некоторый Javascript для обновления токена. Вот ссылке как стартер для решения вашей проблемы.

#1 09.07.2019 16:07:58

Ошибка 419 при любых настройках сессии и формы

Всем привет.
Проблема такая
У меня при отправке формы ошибка 419 page expired.
Перелопатив всё, что нашел в гугле, я пробовал делать следующее:

  • Проставлять права на запись в папке storage (файлы создаются при каждом обновлении страницы новые)

  • Переключился на хранение в БД (новые строки создаются)

  • Прописывал в форме так: @csrf

  • Прописывал в форме так:  <input type=”hidden” name=”_token” value=”{{ csrf_token() }}”>

  • чистил кэши, пересобирал проект после удаления папки “vendor”

Ничего из этого не помогло. Единственным выходом было отрубить эту проверку csrf токена.
Сайт вертится на open server. Laravel 5.8 самая свежая.
Повторюсь, что всё работает, если вырубить проверку токена. МОжет надо что-то с сервером делать?
Код роута:

Route::resource('/admin/regions', 'AdminRegionsController');

В форме:

<form action="{{route('regions.store')}}" method="post">
   @csrf
   <div class="form-group">
      <label for="title">Название</label>
      <input type="text" class="form-control" id="title" name="title" placeholder="">
   </div>
.
.
.
</form>

#2 09.07.2019 16:50:23

Re: Ошибка 419 при любых настройках сессии и формы

Напиши так
@csrf
@method(‘post’)

#3 09.07.2019 17:59:28

Re: Ошибка 419 при любых настройках сессии и формы

Не помогло, всё так же 419

#4 11.07.2019 13:55:31

Re: Ошибка 419 при любых настройках сессии и формы

Эту проблему смог решить переносом в файле app/Http/Kernel.php вызова класса IlluminateSessionMiddlewareStartSession::class из группы $middlewareGroups в глобальную группу $middleware :

protected $middleware = [
        ...
        IlluminateSessionMiddlewareStartSession::class,
    ];

Это, также, решает проблему с выводом ошибок в формах.

Изменено Evgenium127 (11.07.2019 14:46:00)

#5 11.07.2019 15:19:00

Re: Ошибка 419 при любых настройках сессии и формы

Если все делать правильно, никаких ошибок отправки форм не будет, даже без переноса указанного файла. Где-то есть косяк, ищи.

#6 28.02.2020 14:56:26

Re: Ошибка 419 при любых настройках сессии и формы

Посмотри, какие у тебя прописаны допустимые методы для которых не проверятся наличие csrf в IlluminateFoundationHttpMiddleware. Должно быть так:

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

#7 01.03.2020 09:58:17

TrueKanonir

Откуда: Ташкент
Сообщений: 221

Re: Ошибка 419 при любых настройках сессии и формы

Было такое один раз. В моем случае это решилось очисткой кук.

#8 14.05.2020 22:25:36

Re: Ошибка 419 при любых настройках сессии и формы

в файле VerifyCsrfToken.php добавь свое исключение в массив $except = [ ‘api/*’];

#9 20.05.2020 13:27:07

Re: Ошибка 419 при любых настройках сессии и формы

просто напиши вместо @csrf {{csrf_field()}}

#10 27.01.2021 11:17:32

Re: Ошибка 419 при любых настройках сессии и формы

Попробуйте в web.php вставить вот такой роутинг

Route::get(‘/token’, function (Request $request) {
    $token = $request->session()->token();

    $token = csrf_token();
});
документация по csrf lara 8.x

Изменено RussianGrizzly (27.01.2021 11:22:18)

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 AppHttpMiddlewareVerifyCsrfToken::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

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 AppHttpControllers;
use IlluminateHttpRequest;
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 AppHttpControllersHomeController;
use IlluminateSupportFacadesRoute;
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 AppHttpMiddleware;
use IlluminateFoundationHttpMiddlewareVerifyCsrfToken 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 AppHttpMiddleware;
use IlluminateFoundationHttpMiddlewareVerifyCsrfToken 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.

419 page expired laravel; Through this tutorial, you will learn how to fix laravel 419 page expired error in laravel 9, 8, 7, 6, 5 versions.

if you are making form like login, registration, etc, and submitting a it in a Laravel app using ajax and without ajax and you have not added the CSRF token to it, then you will get errors as follow, 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, etc.

How to solve page expired (419) error in Laravel?

The following 3 solutions of 419 status code (unknown status) laravel are also work with laravel 9, 8, 7, 6, 5. 5.5, 5, 4 versions.

  • Solution 1 – Laravel Page expired 419 error on Form
  • Solution 2 – Laravel Page expired 419 error on Ajax
  • Solution 3 – Remove CSRF protection on specific URL

Solution 1 – Laravel Page expired 419 error on Form

In this first solution, open your 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 – Laravel Page expired 419 error on Ajax

Next solution, if your still found status code: 419 unknown status with your ajax request in laravel. So, you can try the following solution.

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);

    },
});

Solution 3 – Remove CSRF protection on specific URL

Visit appHttpMiddleware directory and open VerifyCsrfToken.php file. Then disable CSRF protection field for routes group or specific routes

<?php
namespace AppHttpMiddleware;
use IlluminateFoundationHttpMiddlewareVerifyCsrfToken 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 9, 8, 7, 6, 5 versions.

Recommended Laravel Tutorials

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

View all posts by Admin

Добавить комментарий