Laravel ошибка 419 при отправке post запроса

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

As per my Knowledge there are two methods to solve this

Method 1: Add CsrF Token

Method 2: Exclude URIs from CSRF protection

How to use

Method 1: Add one more variable to your POST request

_token: "{{ csrf_token() }}"

Example for Ajax

req = $.ajax({
    type: "POST",
    url: "/search",
    data: {
        "key": "value",
        _token: "{{ csrf_token() }}",
    },
    dataType: "text",
    success: function(msg) {
        // ...
    }
});

Example if you using forms

<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">

Method 2: There is a file named VerifyCsrfToken in following location

yourProjectDirectory/app/Http/Middleware

Add your URL in following method

 protected $except = [
     'url1/',
     'url2/',
 ];

When To use

  • If you are the owner(full control) of API, use Method 1, as CSRF Token adds security to your application.

  • If you are unable to add CSRF Token like in case if you are using any third party API’s, webhooks etc., then go for Method 2.

Имеем обычную форму, с токеном и POST запросом. В ответ получаю 419 | Page expired.
Перерыл весь гугл, попробовал всё что мог, везде в принципе одно и тоже. Проект новый, с нуля пишу в перывй раз, возможно мог что-то забыть в изначальных настройках ? Какие еще данные нужны, для помощи в отладке ?


  • Вопрос задан

    более трёх лет назад

  • 24518 просмотров

Are you getting the Laravel error 419 session expired during a post request?

This occurs due to CSRF token verification failure, misconfigured cache, permissions, improper session settings, etc.

At Bobcares, we fix Laravel errors, as a part of our Server Management Services.

Today, let’s have a look into the session expired error. We’ll also see how our Support Engineers fix it.

Laravel Error: 419 session expired

Laravel is a web development framework. It allows customizing configuration. And the user/developer can create a .env file for this purpose.

By default, Laravel is an HTTP driven application. The session provides ways to store information. The available options are files, cookie, database, Memcached or Redis, and array.

This error shows up when a user submits a post request. The error in front-end appears as,

Laravel error 419 session expired in front end.

And, in the command line, the error appears as,

419 Sorry, your session has expired. Please refresh and try again.

Many reasons can lead to session expired error. The most obvious reasons are CSRF token failure, cache, permissions, improper session settings.

How we fix the Laravel error 419 session expired?

Our Support Engineers with expertise over a decade in Server Administration fixes Laravel errors. Let’s see the common causes and how we fix it.

1. CSRF token verification failure

The most common reason for the 419 error is CSRF token failure. Cross-site request forgery token is a unique, encrypted value generated by the server.

Laravel generates a CSRF token for each user session. The token verifies the user by requesting the application.

So always include a CSRF token in the HTML form to validate the user request.

The VerifyCsrfToken middleware automatically crosses checks the token in the request to the token stored in the session.

In addition to CSRF token verification, the VerifyCsrfToken middleware also checks the X-CSRF-TOKEN request header.

So, we store the token in the HTML meta tag. Then a library like jQuery can automatically add a token to all request headers. Therefore to fix the CSRF token failure we check the token in the application.

2. Session expired error due to cache

Sometimes, the cache can also lead to session expired error in front-end. This can be both the server cache and browser cache. So, our Support Engineers clear the server cache using

php artisan cache:clear

If this does not fix the error, we ask the customer to clear the browser cache. Many times this fixes the error.

3. Laravel file and folder permissions

Similarly, improper file or folder permission can also lead to errors. Usually, web servers need write-permissions on the Laravel folders storage and vendor. Also, session storage needs write-permission. So, our Support Engineers give permissions as,

chmod -R 755 storage

chmod -R 755 vendor

chmod -R 644 bootstrap/caches

Mostly, this fixes the error.

4. Laravel session setting

Last but not least, session settings can also cause a 419 error. The app/config/session.php is the session config file. Our Experts check the session settings in this file. Hence we correct if there is an error. We always check for a few important parameters – domain and secure.

'domain' => env('SESSION_DOMAIN', null),
'secure' => env('SESSION_SECURE_COOKIE', false), // in case of cookie

These step by step approach fixes the error and make Laravel working again.

[Need assistance in fixing Laravel errors? – Our Experts are available 24/7.]

Conclusion

In short, the Laravel error 419 session expired occur due to many reasons like CSRF token failure, wrong cache, permissions, improper session settings, etc. Today, we saw how our Support Engineers fix this error.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Answer by Shawn Weeks

Stack Overflow for Teams
Where developers & technologists share private knowledge with coworkers

,

Meta Stack Overflow

,When I try to test this api on GET /person it works fine but on POST and PUT I am getting a 419 status code from Laravel.,Stack Overflow en español

Typically, you should place these kinds of routes outside of the web middleware group that the RouteServiceProvider applies to all routes in the routes/web.php file. However, you may also exclude the routes by adding their URIs to the $except property of the VerifyCsrfToken middleware:

<?php

namespace AppHttpMiddleware;

use IlluminateFoundationHttpMiddlewareVerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
        'http://example.com/foo/bar',
        'http://example.com/foo/*',
    ];
}

Answer by Lilianna Gould

If you are developing REST APIs, you better not add tokens. If you are using 5.4 or 5.5 you can use api.php instead of web.php. In api.php you don’t need token verifcation on post requests.,If you are using web.php, then you can exculde routes that you don’t want to validate with CSRF Tokens.,I am succesfully calling a REST API with the following code However I would like to get both the header value-(201) and Response Body that are returned after th…,I have added this line of code to create this route in my routes/web.php file:

I am trying to create a RESTful API by using Laravel. I have created my controller using php artisan make:controller RestController and this is my controller code:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class RestController extends Controller
{
    private $arr = array(
            array("name"=>"jon", "family"=>"doe"),
            array("name"=>"jhon", "family" => "doue")
        );
    public function index(){
        return json_encode($this->arr);
    }

    public function store(Request $request){
        return "oops!!";
    }

    public function update (Request $request, $id){
        return "test";
    }

}

I have added this line of code to create this route in my routes/web.php file:

Route::resource('person', 'RestController');

Typically, you should place these kinds of routes outside of the web middleware group that the RouteServiceProvider applies to all routes in the routes/web.php file. However, you may also exclude the routes by adding their URIs to the $except property of the VerifyCsrfToken middleware:

<?php

namespace AppHttpMiddleware;

use IlluminateFoundationHttpMiddlewareVerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
        'http://example.com/foo/bar',
        'http://example.com/foo/*',
    ];
}

Answer by Judith Wong

The following 3 soluction of 419 status code (unknown status) laravel are also work with laravel 7, 6, 5. 5.5, 5, 4 version.,Next, open again your blade view file. Then get the csrf token and add with ajax code in laravel:,419 status code laravel. Here we will show you 3 solutions of status code 419 unknown status.,Next solution, if your still found status code: 419 unknown status with your ajax request in laravel. So, you can try the following solution.

In this first solution, 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>

Next, open again your blade view file. Then get the csrf token and add with ajax code in laravel:

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

$.ajax({

});

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

    },
});

Answer by Pearl Solis

<meta name="csrf-token" content="{{ csrf_token() }}">
//if not work
composer dump-autoload

Answer by Davian Magana

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.,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.,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.,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.

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() }}">

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>
<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!");
});

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
    ];
}

Понравилась статья? Поделить с друзьями:
  • Laravel 500 ошибка после переноса
  • Laptop kernel power 41 причины ошибки
  • Land rover ошибка стояночного тормоза
  • Land rover discovery ограничение мощности ошибка
  • Land rover discovery коды ошибок