AlexBisoft's avatar

Post request in Laravel 5.7 --- Error - 419 Sorry, your session has expired.

I installed Laravel 5.7

Added a form to the file \resources\views\welcome.blade.php

            <form method="POST" action="/foo" >
                @csrf
                <input type="text" name="name"/><br/>
                <input type="submit" value="Add"/>
            </form>

Added to file \routes\web.php

    Route::post('/foo', function () {
        echo 1;
            return;
        })

After sending POST request:

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

In version 5.6 there was no problem.

CSRF token is in the session file.

Middleware VerifyCsrfToken does not receive a token.

0 likes
45 replies
Snapey's avatar

Have you changed session domain at all?

config session.php

'domain' => env('SESSION_DOMAIN', null),

or set SESSION_DOMAIN in the .env file?

AlexBisoft's avatar

I have

'driver' => env('SESSION_DRIVER', 'file'),
'files' => storage_path('framework/sessions'),
'domain' => env('SESSION_DOMAIN', null),

What value should you put in place of null? http://mysite.loc/ ? localhost ?

AlexBisoft's avatar

The files evn. and session.php are the same as the Laravel 5.6 files, where there are no problems.

Snapey's avatar

setting the session domain can cause problems, so its not that.

AlexBisoft's avatar

I can turn off route verification in VerifyCriefToken. But it's bad. Developers Laravel in version 5.7 that something new came up in the middleware VerifyCriefToken.

AlexBisoft's avatar

I do not think that the port influences the work of the VerifyCsrfToken intermediary.

If you disable the csrf-verification POST request is processed. But it's really bad to turn off the verification.

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
/**
 * Indicates whether the XSRF-TOKEN cookie should be set on the response.
 *
 * @var bool
 */
protected $addHttpCookie = true;

/**
 * The URIs that should be excluded from CSRF verification.
 *
 * @var array
 */
protected $except = [
    '\foo',
    //
];
}
jimmy.puckett's avatar

I am having this same issue on 5.7 with my test on my ci runner. The test run fine locally, but give this 419 error on the runner. I have dug & dug into this, but cannot find an answer.

Did anyone come up with a solution?

AlexBisoft's avatar

Have you tried to turn off the middleware VerifyCriefToken check?

jimmy.puckett's avatar

@AlexBisoft the VerifyCsrfToken is disabled by default when running as test env. Plus it runs & passes locally. Just not on the CI server where the other 310 test & 676 assertions do run and pass. It is just a few specific test.

Here is an is one of the broken feature test...

    /**
     * @test
     */
    public function it_redirects_registered_user_to_app_home()
    {
        /** @var User $user */
        $user = factory(User::class)->make();
        /** @var Organization $organization */
        $organization = factory(Organization::class)->make();

        $this->post(
            route('register'),
            [
                'email'                 => $user->email,
                'first_name'            => $user->first_name,
                'last_name'             => $user->last_name,
                'organization'          => $organization->name,
                'password'              => 'secret',
                'password_confirmation' => 'secret',
            ]
        )
             ->assertRedirect(route('app.home'));
    }

the output on the ci...

Tests\Feature\Authentication\RegistrationTest::it_redirects_registered_user_to_app_home
Response status code [419] is not a redirect status code.
Failed asserting that false is true.
AlexBisoft's avatar

jimmy.puckett Divide into 2 steps. And if you can see which object $this->post() gives.

jimmy.puckett's avatar

@AlexBisoft Ya, I know what it gives...

    <body class="antialiased font-sans">
        <div class="md:flex min-h-screen">
            <div class="w-full md:w-1/2 bg-white flex items-center justify-center">
                <div class="max-w-sm m-8">
                    <div class="text-black text-5xl md:text-15xl font-black">
                        419                    </div>

                    <div class="w-16 h-1 bg-purple-light my-3 md:my-6"></div>

                    <p class="text-grey-darker text-2xl md:text-3xl font-light mb-8 leading-normal">
                        Sorry, your session has expired. Please refresh and try again.                    </p>

                    <a href="http://localhost">
                        <button class="bg-transparent text-grey-darkest font-bold uppercase tracking-wide py-3 px-6 border-2 border-grey-light hover:border-grey rounded-lg">
                            Go Home
                        </button>
                    </a>
                </div>
            </div>

            <div class="relative pb-full md:flex md:pb-0 md:min-h-screen w-full md:w-1/2">
                <div style="background-image: url('/svg/403.svg');" class="absolute pin bg-cover bg-no-repeat md:bg-left lg:bg-center">
</div>
            </div>
        </div>
    </body>

As you can see if is a Sorry, your session has expired. Please refresh and try again. error, which is the 419.

I am just not sure what is unique to the runner that is causing the test to not work, but they work on all of our dev machines.

There just appears to be something particular about some setups that is causing issues with sessions?

I was hoping that whatever was done on this thread might help point me/others in the right direction.

AlexBisoft's avatar

jimmy.puckett Try to look like this:

$organization = factory(Organization::class)->make();

dd($user);

And then so:

dd( $this->post( route('register'), [ 'email' => $user->email, 'first_name' => $user->first_name, 'last_name' => $user->last_name, 'organization' => $organization->name, 'password' => 'secret', 'password_confirmation' => 'secret', ] ) );

AlexBisoft's avatar

although you have a problem in time $this->post( ... )

msyadav's avatar

Did anyone got the solution of 419 error please?

jimmy.puckett's avatar

@msyadav We have not been able to replicate the issue consistently, so we have not been able to pin point it. In our situation, it is only happening on select systems, so it has to be some environmental issue. We are running on systems in docker with the exact same docker image, but there is slight different configurations (locally we run as docker-compose with a few configs in .env & on CI server, we run with all envs passed into system). They are however using the same keys & database (sqlite in memory).

We have seen a few post on this topic on the GitHub repo too...

https://github.com/laravel/framework/issues/26106

Hopefully someone will find the pattern to the issue.

AlexBisoft's avatar

I noticed all the errors in version 5.7 are displayed differently than in 5.6. Other design and picture added. Perhaps the answer is formed as something else. Tokins at each request and they most likely do not match when checking. Possibly the Responsa object is sent twice.

AlexBisoft's avatar
AlexBisoft
OP
Best Answer
Level 1

I installed the framework v 5.7.9 the problem disappeared. Old version 5.7.6.

jsanbae's avatar

is there no error in storage/logs/laravel.log file? I had permission problems with the session directory after that the problem solved

ganeshkhadka's avatar

This problem is related to cache. If you are running in chrome then simply press ctrl+shft+i .There you can see the inspect.Then simply hard reload the page.For this simply press ctrl+shft+R. and run your url. It works for me. Thanks

andres_gcarmona's avatar

I got the same issue after updating to 5.7.13. I think the issue has to do with the way the cookies are now encrypted.

What I did was to regenerate the app keys with php artisan key:generate and the problem was gone!.

NL's avatar

Upgraded to both 5.7.9 and latest 5.7.14 - didn't help. php artisan key:generate didn't help. Using @csrf and old approach {{ csrf_field() }} didn't work. Disabling in VerifyCsrfToken middleware the only thing that works. Cache is using Redis (not file system -> no issues with file permissions, but even 777\755 didn't help).

greizd's avatar

Also the reason could be wrong system date.

iEXTRA's avatar

I solved this problem by changing PHP version to 7.2

ma_dev's avatar

I went through the github link posted by @jimmy.puckett and I am still getting the same error. I tried in both Firefox and Chrome and I still get the same error. I am doing this in a brand new Laravel project using Laravel 5.7.19.

Has anyone been able to resolve this issue yet?

khanhvo's avatar

I got same error of this thread and I tried check token on login page and token value in session (I checked in middleware VerifyCsrfToken). Surprisingly, It's different.

Store {#235 ▼
  #id: "Wqj96IDXb6Kj2E2lEXzaTz6PCzDCoJd6dED63XxB"
  #name: "ws_bookshelf_session"
  #attributes: array:1 [▼
    "_token" => "X5ZJ6EGCddrF7SH5mXI5aR9Jjr7jEtI9IOhGZCG4"   
  ]
  #handler: FileSessionHandler {#236 ▼
    #files: Filesystem {#110}
    #path: "/app/storage/framework/sessions"
    #minutes: "120"
  }
  #started: true
}

Token in my page _token: 52i5bj33Gtpckdso2qOhGkJq4oHxHIknKZXx6HoA

Thats why we always get 419 page. I think somewhere renew my token after I click submit bution at login form.

Now I trying to find out that on my project.

My guess: Laravel have login function maybe we used same route with that page and token was renewed after we submit.

diadal's avatar

what is the best way to fix this on Laravel Framework 5.7.22

Next

Please or to participate in this conversation.