Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired
Asked Answered
D

48

180

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 a POST request:

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

In version 5.6 there was no such a problem.

Delmadelmar answered 1/10, 2018 at 2:25 Comment(13)
Have you tried adding a redirect? Instead of return; you can call return redirect()->back();. From what I can see, the app has nothing to do after the post request. Maybe you can redirect it to a view after processing the request.Honestly
I'm having the same issue. When i switch to database session this happens and when i change back to file for SESSION_DRIVER in .env it works fine. Why is the database based session not working.Anemometry
I copied your exact code into a fresh laravel 5.7 install. It worked. There is a problem elsewhere.Chun
this problem because of token problem. I have try to run same code like this, but get no error. You should give more information like your session driver, _token value display in the form. Also, you can debug yourself in this file vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php line 67 to know whyBryan
I realized that I had used sessions table for a different purpose. After Changing this table name to a more suited one and ran artisan session:table and refreshed migration everything is working fineAnemometry
I tested your code and found no problem. It showed no warning message and echos 1 accurately. I am also using laravel 5.7Perennial
Sessions are supposed to expire, so just to check the obvious question - how long was the form open for before you submitted it? What is the value of lifetime in config/session.php?Troutman
Since the OP author didn't chime in and tell what solved his problem. I see a lot of solutions here which didn't solve the issue I had. I solved it differently, so no one answer is correct I guess. All of them may be correct in different scenarios. Hence I hold my bounty offer.Anemometry
You can add an answer which solved your problem unless its referenced in any answers here (because it doesn't make sense). And according to you which answer you have liked the most/more suitable for future OP's you can award the bounty. because you can't get the bounty points back at any circumstancesPutrid
if you will need to exclude your response route from CSRF protectionScummy
#37807262Outwardbound
After trying every clear commands (optimize:clear, route:clear etc ) i run "php artisan config:cache" Then it fixed the issue for 419 page expired on live server.Allegorical
always include csrf data in your html header like this <meta name="csrf-token" content="{{ csrf_token() }}"> and include another in your form via @csrf. Use developer inspection view on the browser to check if they both match and you don't have some javascript messing up the CSRF data in the form (as was my case). It's a good place to start troubleshooting.Eighteen
P
263

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

Putrid answered 11/11, 2018 at 20:59 Comment(5)
Sometimes it's just that browsers, mainly Chrome won't put the Set-Cookie session value because it's malformed or non-standard. So Laravel won't find any existing session value from the HTTP request to compare to the received _token value from the FORM. Avoid using SESSION_DOMAIN=... with IP which Chrome and HTTP Cookie Specs consider as insecure.Penoyer
I have the same problem, but I do not recieve the error constantly. It just occures from time to time. I guess that means there's no problem with the session driver, because it works 99% of the time. But I'm running a live app and I get complaints from clients from time to time. It is very rare though. I am using the file session driver. Does someone know why this happens in my case? Thank youYevette
@TheAngelM97 You can easily reproduce this error by going to either the login or register page. Don't do anything for, maybe, more than 30 minutes. Then when you click on submit, the 419 Page Expired shows up. For usability's sake, how do you tell a simple user what just has happened and how to solve it?Hefter
What's the difference between using @csrf or {{ csrf_field() }}? Is it the same thing?Jaela
it is the same thing. just two ways of doing it.Putrid
W
57

This is because the form requires a csrf. In version 5.7, they changed it to @csrf

<form action="" method="post">
    @csrf
    ...

Referene: https://laravel.com/docs/5.7/csrf

Wager answered 10/10, 2018 at 3:1 Comment(4)
His form includes a csrf token. Not sure if he edited it later or not.Contracture
yeah, his form originally has a csrf field, I just looked into the edit historyDoralyn
This does not solve the issue in my case too, as I always have it in my form, but started facing error due to some of other changeShrewsbury
even with the csrf set I'm getting the same error...Envenom
E
37

case 1 : if you are running project in your local system like 127.0.01:8000 ,

then

add SESSION_DOMAIN= in your .env file

or in your config/session.php 'domain' => env('SESSION_DOMAIN', ''),

and then run php artisan cache:clear

case 2: if project is running on server and you have domain like "mydomain.com"

add SESSION_DOMAIN=mydomain.com in your .env file

or in your config/session.php 'domain' => env('SESSION_DOMAIN', 'mydomain.com'),

and then run php artisan cache:clear

Ewe answered 6/2, 2019 at 20:14 Comment(2)
Having no experience with php, this was key to getting the web app up and running on an aws ec2 instance. Thanks!Teen
Thanks @Saurabh, changing the session domain to SESSION_DOMAIN= when running over localhost did the trick.Genius
I
12

How about using

{{ csrf_field() }} instead of @csrf

419 error is mostly because of csrf token issues.

Irredeemable answered 5/11, 2018 at 12:5 Comment(2)
It generates same html as @csrf does so same resultShrewsbury
Hi Bonish already have @csrf used inside form. I have same error result which is 419 error.Portia
D
12

It should work if you try all of these steps:

  1. Ensure that your session is well configured, the easiest way is to make it file and make sure storage folder has chmod 755 permission then in your .env you set it like below, file session driver is the easiest way to set.

    SESSION_DRIVER=file
    SESSION_DOMAIN=
    SESSION_SECURE_COOKIE=false
    
  2. Ensure Cache folder is cleared and writable, you can do this by running below artisan command.

    php artisan cache:clear
    
  3. Ensure folder permissions are well set, they should be configured like below:

    sudo chmod -R 755 storage
    sudo chmod -R 755 vendor
    sudo chmod -R 644 bootstrap/cache
    
  4. Ensure your form has @csrf token included.

Hope this will solve your problem.

Dania answered 15/7, 2020 at 6:35 Comment(3)
the sudo setting of permissions crashed my laravel completely.Lasting
This is what worked for me. in my case i was facing the issue when i try to serve on host instead of localhost.Zebrass
I think you should keep the chmod -R 644 bootstrap/cache writable, otherwise you might get an error.Salutation
H
11

I use Laravel 5.7 I had the same problem and it was because the csrf token wasn't in the form, so adding

@csrf

fixed the problem

Hoke answered 14/12, 2018 at 14:31 Comment(0)
U
11

It could be a problem with your session. After playing around with these settings I resolved my problem. For me it turned out to be the last option.

  • If you are using "file" as session driver look into storage/framework/sessions if the sessions are getting saved after a refresh. If not It is most likely due to incorrect folder permissions. Check that your storage/ folder have the correct right
  • Try to disable all the Javascript in your pages (either by disabling it via navigator or inside the code) and make sure that 'http_only' => true,
  • Try to use with and without https
  • Make sure the SESSION_DRIVER variable is NOT null
  • Try to switch between 'encrypt' => false, and 'encrypt' => true,
  • Try to change the cookie name 'cookie' => 'laravelsession',
  • Try either to set your SESSION_DOMAIN to your actual domain OR null
  • Try to switch between 'secure' => env('SESSION_SECURE_COOKIE', false), and 'secure' => env('SESSION_SECURE_COOKIE', true),

Source:Laravel Session always changes every refresh / request in Laravel 5.4

Unfruitful answered 11/10, 2019 at 5:11 Comment(3)
Yes, after try many other things, the SESSION_SECURE_COOKIE switch (changed it to false) did it for me. (on localhost:8000)Eastlake
SESSION_SECURE_COOKIE was also the problem for me, I it changed it when following a guide for website optimization.Unfruitful
for me it works with https but not with http... any idea why? thanks for the great answer, took me hours to find it.Appraise
P
9

Try to comment out \App\Http\Middleware\EncryptCookies::class in \app\Http\Kernel.php I have similar problem and solved it by doing so. Probably not the best solution because the security but at least it worked.

Previously I tried:

  • Clear cache
  • Generate new app key
  • Run my app in various Browsers (Chrome 70, Mozilla Firefox 57, and IE 11)
  • Run my app in another computer
  • Comment out \App\Http\Middleware\VerifyCsrfToken::class in \app\Http\Kernel.php
  • Comment out \Illuminate\Session\Middleware\AuthenticateSession::class in \app\Http\Kernel.php
  • Upgrade and downgrade Laravel (between 5.6 and 5.7)

But none of these above worked for me.

EDIT

My case here is every time I login, a new session file will be created (The old one is still persist, but suddenly forgotten. Check storage/framework/sessions) and new CSRF token is generated. So the problem is not with VerifyCsrfToken.

As @Vladd mentioned in comment section, you should never comment out \App\Http\Middleware\VerifyCsrfToken::class. You have to check that you sent the right CSRF TOKEN to the server.

Perversion answered 3/12, 2018 at 4:10 Comment(4)
Among those ways you mentioned, only commenting out \App\Http\Middleware\VerifyCsrfToken::class in \app\Http\Kernel.php worked for me.Margetmargette
Clear cache, Generate new app key + Remove cookiesGantlet
You never shall c0mmenting out \App\Http\Middleware\VerifyCsrfToken::class. Why would you do that? To create your self weak point in app?Wound
@Gantlet Thanks for adding '+ Remove Cookies' because I was getting a 419 error even after doing everything I possible could and it only worked when I cleared the browser cookies / tried in incognito.Profile
Z
9

419 | page this error means laravel security issue it means csrf token field is not used correctly.

use {{csrf_field}} and your issue will be solved.

Zephan answered 15/9, 2019 at 0:6 Comment(0)
K
9

To solve this error you first need to insert one of the following commands into the form tag.

@csrf OR {{ csrf_field }}

If your problem is not resolved, do the following: (Note that one of the above commands must be in the form tag)

1.Insert one of the following commands into the form tag @csrf OR {{ csrf_field }}

2.Open the .env file and change the values ​​to the "file" in the SESSION_DRIVER section.

3.Then you should reset laravel cache. type below commands in the terminal

php artisan view:clear php artisan route:clear php artisan cache:clear

php artisan config:cache

4.In the final step, unplug the project from the serve and click again on php artisan serve

I hope your problem is resolved

Kilter answered 2/3, 2020 at 12:36 Comment(1)
Thank you @hosein azimi, you fixed my problem. Using Laravel 9Portia
C
8

ob_start();

This problem take more than two days with me the solution was simple :

go to public folder and add this ob_start(); in first line in index.php

Important: after that clear cache of browser. you can follow this guide to clear your browser's cache

Corsair answered 6/10, 2021 at 1:0 Comment(1)
amazingly it worked .. but could not get the reason ... it has been on my local docker but suddenly appeared 419 error on every requestGschu
P
7

Please also update CSRF in header

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

Update CSRF in Form

@CSRF

if you have already CSRF in header and Form then Go To config/session.php and update

'domain' => env('SESSION_DOMAIN', 'example.com'),[ Only Domain name without https ]
Peril answered 17/3, 2022 at 11:31 Comment(1)
One time Ii have faced such a type of error. It was resolved due to removing https from the URLKappenne
P
6

change your @csrf in welcome.blade.php to <input type="hidden" name="_token" value="{{ csrf_token() }}">

so your code like this:

<form method="POST" action="/foo" >
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <input type="text" name="name"/><br/>
    <input type="submit" value="Add"/>

   <button type="submit">Submit</button>
</form>
Perfervid answered 16/2, 2019 at 9:47 Comment(0)
H
5

Go to config/sessions.php

find the row

'secure' => env('SESSION_SECURE_COOKIE', true),

change it to false

'secure' => env('SESSION_SECURE_COOKIE', false),

If this parameter is set to TRUE browser will require you to use HTTPS protocol, otherwise it wont store the session. As it is not valid

Hamm answered 4/8, 2020 at 8:11 Comment(0)
T
4

There is no issue in the code. I have checked with the same code as you have written with new installation.

Form Code:

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

web.php file code:

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

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

The result after submitting the form is: Output after submitting the form

If you clear your browser cache or try with other browser, I think it will fixed.

Tillotson answered 11/11, 2018 at 12:34 Comment(0)
B
4

A quick bad approach is that go to app\http\middleware\verifycsrftoken.php and add the route in $except list. The post request will be ignord for CSRF Token verification.

protected $except = [
    //
    'doLogin.aspx',
    'create_coupon',
];
Blairblaire answered 11/11, 2018 at 13:33 Comment(1)
This is a great option if you want to accept POST webhooks!Acrobatic
T
4

open command line cmd on your project.

1.command

php artisan config:cache

2.comand

php artisan route:clear

Don't worry.

This will clear the old cache and route caches. Your code will not change.

I hope this was helpful for you.

Toxicosis answered 4/3, 2020 at 12:59 Comment(0)
A
3

After so much time i got it solved this way

My laravel installation path was not the same as set in the config file session.php

'domain' => env('SESSION_DOMAIN', 'example.com'),
Auberge answered 20/5, 2019 at 19:52 Comment(0)
D
3

add csrf token and your issue will be solved . {{csrf_token}} or @csrf

Durango answered 1/10, 2019 at 19:19 Comment(0)
T
3

While the form has @csrf, it still shows 419 pages has expired

I solved it after update SESSION_SECURE_COOKIE option to false in config/session.php

'secure' => env('SESSION_SECURE_COOKIE', false)

than clear cache

Tune answered 24/7, 2020 at 6:55 Comment(0)
S
3

After many searches I found solution here,

Inside your main index.php file inside public folder, edit it and at the very top write ob_start()

Staw answered 27/9, 2021 at 14:28 Comment(0)
F
2

It may be overkill but you can try this:

// Form calling named route with hidden token field added.

<form method="POST" action="{{ route('foo') }}" >
    @csrf
    <input type="hidden" name="_token" value="{!! csrf_token() !!}">
    <input type="text" name="name"/><br/>
    <input type="submit" value="Add"/>
</form>

// Named Route

Route::post('/foo', function () {
    return 'bar';
})->name('foo');

// Add this within the <head></head> block:

<meta name="_token" content="{!! csrf_token() !!}" />

I did test it on my local using Homestead on Laravel 5.7 which was was fresh install using Laravel Installer 2.0.1 and it worked. What is your environment?

Theory: I wonder if that has something to do with blade rendering html tags with {{ }} vs. {!! !!} on your environment or how you are serving it (eg. php artisan serve). What makes me think that is line 335 of /vendor/laravel/framework/src/illuminate/Foundation/helpers.php should render the same line manually typed out above.

Favoritism answered 9/11, 2018 at 7:13 Comment(2)
Yeah cool, but <meta> tags should be placed within the <head>, not inside the <body>. I'm not sure HTML validator would like this.Sofar
I would say you are correct and that should be moved to the head.Favoritism
T
2

If you already have the csrf directive, you might have changed the way sessions runs.

In config/session.php, check the 'secure' field. It should be on false if https isn't available on your server.

You can also put SESSION_SECURE_COOKIE=FALSE on your .env file (root directory).

Ticking answered 16/11, 2019 at 11:3 Comment(0)
L
2

For me the error comes once the session become invalid and user tries to submit the post request. The csrf_token were no longer valid. so I overcomes it by changing the Handler.php in Exceptions directory and try catch the token mismatch exception like this.

The render function was like this

public function render($request, Exception $exception)
{
    return parent::render($request, $exception);
}

Then I modify it to look like this

public function render($request, Exception $exception)
{

    if ($exception instanceof \Illuminate\Session\TokenMismatchException){ // <<<=========== the Code
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        return redirect('/home')->with('message', 'You page session expired. Please try again');
    }
    return parent::render($request, $exception);
}

Simply you choose the route that can handle the token refresh operation.

Lashing answered 1/2, 2020 at 8:13 Comment(0)
C
2

I tried all the answers provided here. However none of them worked for me in shared hosting. However, soultion mentioned here works for me How to solve "CSRF Token Mismatch" in Laravel l

Commonable answered 17/8, 2020 at 5:48 Comment(0)
S
2

In my case was a missing ?> at the end of routes/web.php.

Spoonful answered 9/10, 2020 at 20:20 Comment(3)
same, I've forgot to add ?> to end of web.phpBlaineblainey
WOW. Not exactly the same problem in my case, but your solution made me check this, and when I did, I noticed whitespace before the opening <?php tag, and that's what was causing a 419 on every form on the site! Oddly, it didn't happen with PHP 7.3, and started after upgrading to 7.4!Stirps
In fact, simply adding/removing a paragraph from that file has the same effectHamadryad
R
2

2021, I faced this error while applying all above solutions, my every route was throwing 419. My app was working fine on localhost but 419 on server. Then I got solution while fixing .env file on production, remove sanctum variables from .env and set 'secure' => env('SESSION_SECURE_COOKIE', null) in config/session.php

Row answered 7/7, 2021 at 4:53 Comment(0)
A
1

I just had the exact same issue and it was down to me being completely stupid. I had disabled all of the form fields (rather than just the submit button) via javascript before submitting said form! This, of course, resulted in the all the form elements not being submitted (including the hidden _token field) which in turn brought up the 419 error!

I hope this helps someone from a few hours of head scratching!

Disabled form inputs do not appear in the request

Affiliation answered 14/10, 2018 at 19:38 Comment(0)
E
1

In your Http/Kernel.php

try to comment this line :

\Illuminate\Session\Middleware\AuthenticateSession::class,

in your web middleware array

it might be the root of your issue

Eliason answered 6/11, 2018 at 12:11 Comment(0)
N
1

Actually CSRF is a session based token. Add your route in a route group and add a middleware which control the sessions.

web is a default middleware in laravel and it can controls the session requests.

Route::group(array('middleware' => ['web']), function () {
  Route::post('/foo', function () {
     echo 1;
     return;
  });
});
Nashner answered 11/11, 2018 at 17:25 Comment(0)
R
1

In default I didn't have this problem. So what I did is chmod -R 644 sessions to replicate the problem.

enter image description here

Afterwards I gave permissions to sessions folder by chmod -R 755 sessions

now my project code works again.

enter image description here

Reason it happens is you store your cache on file with lack of writing permissions.

The session configuration file is stored at config/session.php. Be sure to review the options available to you in this file. By default, Laravel is configured to use the file session driver, which will work well for many applications. In production applications, you may consider using the memcached or redis drivers for even faster session performance.

Solutions:

1 - As I have fixed above you can give 755 permission to sessions folder. 2 - You can use another session driver configuration.

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.

Bear in mind; If you want to use memcached/redis you need to have them installed on your server or your docker redis container must be running.

Ruinous answered 12/11, 2018 at 8:58 Comment(0)
A
1

Do you also have the csrf in the header of your application?

<meta name="csrf-token" content="{{ csrf_token() }}">
Alee answered 12/3, 2020 at 6:4 Comment(0)
P
1

In my case I resolve mine when I had a debugging tool called barryvddh/laravel-debugbar by jnoordsij

Here is the link of the debugging tool which I recommend

Installation method

Require this package with composer. It is recommended to only require the package for development.

composer require barryvdh/laravel-debugbar --dev

Laravel uses Package Auto-Discovery, so doesn't require you to manually add the ServiceProvider.

The Debugbar will be enabled when APP_DEBUG is true.

If you use a catch-all/fallback route, make sure you load the Debugbar ServiceProvider before your own App ServiceProviders.

Laravel without auto-discovery: If you don't use auto-discovery, add the ServiceProvider to the providers array in config/app.php

Barryvdh\Debugbar\ServiceProvider::class,

If you want to use the facade to log messages, add this to your facades in app.php:

'Debugbar' => Barryvdh\Debugbar\Facades\Debugbar::class,

The profiler is enabled by default, if you have APP_DEBUG=true. You can override that in the config (debugbar.enabled) or by setting DEBUGBAR_ENABLED in your .env. See more options in config/debugbar.php You can also set in your config if you want to include/exclude the vendor files also (FontAwesome, Highlight.js and jQuery). If you already use them in your site, set it to false. You can also only display the js or css vendors, by setting it to 'js' or 'css'. (Highlight.js requires both css + js, so set to true for syntax highlighting)

Copy the package config to your local config with the publish command:

php artisan vendor:publish --provider="Barryvdh\Debugbar\ServiceProvider"

While using debug bar tool I've seen that Laravel initially selects * from sessions, having a column name id containing string so, I replaced the datatype from int to string

Then I looked for the migration file having sessions table file

I removed the duplicate migration file sessions table file

database/migrations/202_08_02_063945_create_sessions_table.php

I replaced the columns inside the sessions table

From

public function up()
{
    Schema::create('sessions', function (Blueprint $table) {
        $table->increments('id');
        $table->foreignId('user_id')->nullable()->index();
        $table->string('ip_address', 45)->nullable();
        $table->text('user_agent')->nullable();
        $table->longText('payload');
        $table->integer('last_activity')->index();
    });
}

To

public function up()
{
    Schema::create('sessions', function (Blueprint $table) {
        $table->string('id')->primary();
        $table->foreignId('user_id')->nullable()->index();
        $table->string('ip_address', 45)->nullable();
        $table->text('user_agent')->nullable();
        $table->longText('payload');
        $table->integer('last_activity')->index();
    });
}

Then migrate the sessions table only

In my case:

php artisan migrate:refresh --path=/database/migrations/202_08_02_063945_create_sessions_table.php

Then serve

php artisan serve

I hope this solves error 419 on registration and login issue including page session expired error

All the credits for solving belongs to jnoordsij for making the debugging tool

Portia answered 22/8, 2022 at 2:17 Comment(0)
P
1

Sometimes it could be if you're using ULID or UUID field in users table. You may miss to change foreignUlid field in sessions table:

Schema::create('sessions', function (Blueprint $table) {
        $table->string('id')->primary();
        $table->foreignUlid('user_id')->nullable()->index();
        $table->string('ip_address', 45)->nullable();
        $table->text('user_agent')->nullable();
        $table->longText('payload');
        $table->integer('last_activity')->index();
    });

The reason is Laravel can't create session

Patentee answered 28/6, 2023 at 10:30 Comment(1)
I really wanted to get the database driver working instead of using file-based sessions, and this is ultimately what did it for me. If you're using a ULID or UUID for the users table, the default migration that sets up the sessions table won't work. Make sure the foreign key in the sessions table matches the format of the users table key. (Sounds obvious, but I spent way too much time debugging this.)Fillin
I
1

for me, issue was with 'same_site' setting in config/session.php file

just disable/comment this line (or set it to null) :

#'same_site' => null

I have also set 'secure' and 'domain' to following values :

'secure' => false,
'domain' => env('SESSION_DOMAIN', '')

now my laravel project and login works within localhost, dev domain, and production domain. and login via mobile browsers works finaly (which returned 419 error on chrome and safari). also users can log in to our production domain via iframe (wordpress plugin usage)

hope this helps somebody

Irwinirwinn answered 24/8, 2023 at 9:38 Comment(0)
M
0

I also had a problem like this and I've discovered that the session files were locked for writing. So, I don't know if you are running your Laravel via stuff like vagrant or Docker, but I advise you to try to change the rights of the session directory (and files of course) (When you run Laravel in a VM you should change the rights locally and in the VM (like, when you share the files via NFS)

Like this:

chmod -R 777 storage/framework/sessions
chmod -R 777 storage/logs

I know, a 777 permission is the worst disaster that you can ever imagine. But they are handy for troubleshooting.

To be sure that I never forgot this I made a bash script. (Called it lalog, just because I wanted to clear the log files and set permissions)

Note: Make sure that you use this on the session directory. In config/session.php there is a files key declared with the location. In my case:

<?php
//...........
'files' => storage_path('framework/sessions'),
//...........

Location: /usr/bin/lalog (This is a file, not a directory)
Execute in shell as lalog

#!/bin/bash
rm -rf /home/username/Projects/x/storage/logs/laravel.log
echo "Laravel log removed"
touch /home/username/Projects/x/storage/logs/laravel.log
echo "Laravel log created"
chmod -R 777 /home/username/Projects/x/storage/
echo "CHMOD 777 on Storage dir"

Warning! This will allow write access for everyone, so be carefull with it! Also, maybe there is some usefull information in the log file of Laravel. (be sure to look in that log file before running my bash script)

Also, I know that it's already mentioned. But, be totally sure that you always

  1. Allow cookies in the browser, so the token can be set in the cookies
  2. Check if you are using the @csrf in your blade file

The form should be something like this

<form method="POST" action="{{ route('login') }}">
@csrf
.......
</form>
Misanthropy answered 9/11, 2018 at 7:39 Comment(0)
G
0

Please note you get error 419 if you are trying to upload a big file that exceeds the post file size limit. In this case you can increase both upload_max_filesize and post_max_size to a reasonable amount, (e.g. 10M or 20M depends on your use case and resources), check here: https://mcmap.net/q/64268/-change-the-maximum-upload-file-size

But this may cause resource consumption issues, e.g bandwidth and storage. As a solution you can check the file size before submitting the form and show a warning message.

Guileful answered 13/8, 2019 at 11:43 Comment(0)
R
0

In my case deleting bootstrap/cache fixed the problem

Ronn answered 9/1, 2020 at 5:16 Comment(0)
A
0

I just went throughout this and I hovering here for an answer.. In my case the solution was to clear the browser history.

August answered 29/8, 2020 at 17:43 Comment(0)
L
0

For cloudways users,

Try to disable Varnish (caching layer) from Application Settings.

Lousewort answered 19/10, 2021 at 10:47 Comment(0)
I
0

1 - Go to Public folder open index.php after <?php ob_start()

This function will take the contents of the output buffer and returns a string that is to be sent to the browser for rendering and removes the spaces or line breaks you put before starting PHP.

2 - php artisan cache:clear

Indifference answered 15/9, 2022 at 11:13 Comment(0)
A
0

Not much has been said about those who use external js file: I had a similar issue. I had everything working well inside my blade file. But when I transferred all my js codes to external file, it stopped working.

First ensure that you have this in your app header : // <meta name="csrf-token" content="{{ csrf_token() }}>" //

I have a default header for that at app.blade.php

Secondly in your form you should have something like this

<form  action="" >
    {{ csrf_field() }}  
    ........ </form>

Thirdly in your external js file check this guys post https://mcmap.net/q/137879/-laravel-5-csrf-global-token-hidden-field-for-all-forms-in-a-page . Mine I placed the code at the top of my js file and used the "crsf" variable directly as token. i.e:

token=csrf;
$.ajax({
    url: 'yoururl', //change all these to suit your need.
     type: 'POST',
     data: 
    _token: token, 
     any_other_variables:here });   //etc..

Then clear your cache: php artisan cache:clear

Aspirant answered 14/11, 2022 at 13:51 Comment(0)
P
-1

Just to put it out there, i had the same problems. On my local homestead it would work as expected but after pushing it to the development server i got the session timeout message as well. Figuring its a environment issue i changed from apache to nginx and that miraculously made the problem go away.

Primus answered 7/12, 2018 at 17:21 Comment(0)
M
-1

I got this issue long time ago. I remembered it causes permission of storage/framework/sessions. You may want to change it by chmod -R 0777 storage/framework/sessions command. It worked for me.

Modla answered 28/3, 2019 at 1:59 Comment(0)
S
-1

In my case, it is very ridiculous. I get error 419 when I put Auth::routes() at the top of the route file.

Auth::routes();

Route::middleware('auth')->group(function () {
    Route::get('/', 'DashboardController@index')->name('dashboard');
});

And I fixed the error by moving Auth::routes(); to bottom of the route file.

Route::middleware('auth')->group(function () {
    Route::get('/', 'DashboardController@index')->name('dashboard');
});

Auth::routes();

Maybe it can help your case as well. Good luck.

Submersed answered 28/6, 2019 at 16:42 Comment(0)
S
-1

I had the very same problem in my development environment. It was resolved using http://127.0.0.1:8000 instead of http://localhost:8000.

Sall answered 18/12, 2019 at 23:9 Comment(0)
F
-2

You cannot do an empty return on Laravel 5.6 or greater. Laravel always expects a value to be returned. (I know from past experience). This is mainly to do with how PHP 7 handles empty returns.

Fugitive answered 9/11, 2018 at 14:58 Comment(0)
C
-4

Just change .env

SESSION_DRIVER=cookie
Cascade answered 18/5, 2019 at 22:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.