[5.3] "TokenMismatchException in VerifyCsrfToken.php" in Laravel's auth form #15040

Closed
MountainDev opened this Issue Aug 25, 2016 · 80 comments

Projects

None yet
@MountainDev

I use fresh installation of Laravel 5.3. I did the following steps in my Homestead:

laravel new blog
php artisan make:auth
entered proper database configuration in .env
php artisan migrate

That's all I did. Everything wen smoothly but when I submit register form I get:
TokenMismatchException in VerifyCsrfToken.php line 67:

I tried to clean cache and cookies, use different browsers and install Laravel again (also via composer). Some people from Laravel's IRC Chat also confirm that bug too.

@srmklive
Contributor

I just created a fresh installation of Laravel. Can't replicate the issue you mentioned.

@MountainDev MountainDev changed the title from [5.3] "TokenMismatchException in VerifyCsrfToken.php" in Laravel's register form to [5.3] "TokenMismatchException in VerifyCsrfToken.php" in Laravel's auth form Aug 25, 2016
@MountainDev

@srmklive That is possible. On my second computer with different OS and Vagrant installation Laravel's fresh installation works fine. Neverthelss, I've talked with other people on IRC and the issue is real.

@MountainDev

I found out that technically everything is okay. The issue remains but the code seems fine. In vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php I placed dd($request) before throw new TokenMismatchException;. The _token value matches _token input that is in form. So... What is going on?

@GrahamCampbell
Member

Please ask on the forums. I think it's more likely to be an issue specific to you.

@MountainDev

@GrahamCampbell In my opinion it is NOT only specific to me. I can install and use Laravel's 5.2 auth component properly. With 5.3 I get this strange Csrf exception. Also - how this can be specific to me if it's fresh installation and other people have similar issues to me?

@photz
photz commented Aug 25, 2016

I can confirm that the same thing happened to me as well last night using a new installation of Laravel 5.3.1, although I don't use Homestead.

@MountainDev

I figured that out but I still consider this issue as a Laravel problem. Small change in framework's code and everything works fine.
https://laracasts.com/discuss/channels/laravel/53-tokenmismatchexception-in-laravels-auth-form

@UnrulyNatives
UnrulyNatives commented Aug 28, 2016 edited

I struggled with the same issue. Version 5.3.4. I develop on Win 7. The issue is present both on my local env. and on my Digital Ocean server. Ubuntu 16.04 with PHP 7.0

@GrahamCampbell
It is a framework issue and should be addressed. Pls.

@MountainDev

  1. maybe you could create a pull request. Anyway, thank you so much - your solution saved a lot of time for me.
  2. Your hotfix is not always working. Sometimes I need to run php artisan cache:clear to login.
@MountainDev

Glad to help @UnrulyNatives. Sure, I can create a pull request.

@GrahamCampbell can You look at this issue again? As You can see, it IS a framework problem but only in specific environment. As far as I know, framework should run without problems on every development machine/os/whatever.

@MountainDev

So, if @GrahamCampbell is too busy, maybe @taylorotwell can help and figure out this issue?

@ghermans
ghermans commented Sep 1, 2016

@taylorotwell @GrahamCampbell any update regarding this one?

@nguyenphuocnhatthanh

I has same issue.Can anyone fix this issues ? @taylorotwell

@Tjoosten
Tjoosten commented Sep 2, 2016

@taylorotwell same issue affecting my applications.

@srmklive
Contributor
srmklive commented Sep 2, 2016

I can confirm the same issue happened to me twice, while installing a fresh 5.3 application. I added the fix mentioned by @MountainDev, and it worked. I have a generated a PR for this for inclusion in the framework.

@oitsem099

Confirmed just now the issue is real.
I just installed a fresh installation of 5.3 its annoying hahahaha

@ghermans

Can someone reopen this ?

@joelezeu

I used Mozilla Browser and it worked, still experiencing the problem in Chrome.

@oitsem099

Just tried Mozilla same issue.
this is so annoying hahahaha

@adamgriffin93

Why is this closed??

@oitsem099
oitsem099 commented Sep 14, 2016 edited

I don't know with them. its clearly an annoying issue.
the guys have a fix on this but its temporary only.
it involves touching a single line of code in the FileSystem file of Laravel WHICH WE SHOULD NOT BE DOING.

@joelezeu

@MountainDev your fix didn't work for me.

@adamgriffin93
adamgriffin93 commented Sep 14, 2016 edited

@joelezeu
Something that worked for me was clearing my session and using the database driver.

@oitsem099

guys? still no fix to the bug?

@digitalhuman

This bug still exists. I pulled two projects today and this TokenMismatch is still there! Can somebody please look into this seriously istead of ignoring this fail.
Put your egos aside and properly test this and fix it please. Thank you! How many confirmations do you guys need?

@GrahamCampbell @taylorotwell

@taylorotwell
Member

Again, no bug can be confirmed. Here is a literal video recording of me doing it:

http://d.pr/i/13k0P

@digitalhuman

Well even it that is true, which i assume is. Explain why so many people (like hundrets) have this issue then? Stating 'its not a bug' because you coincidently can not reproduce it while other people can is really not helping.

@zmsaunders
zmsaunders commented Sep 26, 2016 edited

I was having this issue this morning, but our app uses spark and we just upgraded to lv5.3 and spark2.0 - Once I updated the version of interceptors.js that our app was using to match the spark version, it resolved it for us. I noticed that without this, the app was in a loop trying to refresh our session tokens. Not sure if that helps anyone else out. I had first tried the file lock update that someone mentioned earlier with no luck, and also tried changing our session drivers without it fixing the bug either. Oddly enough, this only seems to effect our homestead environments, as our staging and production environments don't have this issue at all.

@taylorotwell
Member
taylorotwell commented Sep 26, 2016 edited

@digitalhuman Calm down. Everything will be OK. All I'm saying is that it works on a fresh Laravel application, so there is some inconsistency between your application and a fresh Laravel application that is causing the problem.

Have you looked into the Vue interceptor issue that @zmsaunders mentions? If you are using vue-resource >= 1.x the interceptor in the bootstrap.js file in Laravel should look like this:

Vue.http.interceptors.push((request, next) => {
    request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken);

    next();
});
@digitalhuman

I am calm, that is not the point here :) I tried database sessions, file sessions and redis sessions. All create the same error on my fresh Laravel clone.

Well I remember the same kinda think happening in 5.1. I don't use Vue. What I see that is happening is;

After posting the form; In the constructing of the VerifyCsrfToken class the session CSRF is already different from the the 'input' version. Any idea why?

@taylorotwell
Member

Do you have JavaScript entirely disabled?

@digitalhuman

Nope, since I had the same issue over and over again I just stopped configuring it in more detail. What I did:

composer create-project --prefer-dist laravel/laravel blog
(Since the above creates and sets the key in .env i did not have to run (php artisan key:generate)

php artisan session:table
php artisan make:auth
php artisan migrate

php artisan serve

Load http://localhost:8000
Checked my database for session; its there and valid. Checked the view, there is a crsf token as meta tag and same value in the form. So that works.

I press 'POST", and I always get this "TokenMismatchException in VerifyCsrfToken.php line 67:" error.

@digitalhuman

So; what I just did; Removed the vendor folder. Completely; then: composer install.
Load the form, post it: TokenMismatchException in VerifyCsrfToken.php line 67

I see my session in the 'cookies', developer console and database. They match and are valid.

@morloderex
Contributor

@digitalhuman I've had the excat some problem some time ago while migrating from a a single server setup to a loadbalancing setup with 2 servers running under it.
And i figured out that for some reason the database driver where not using the same row again, it was always creating a new one.

Not sure about what's going on tho, but we managed to make it work by forcing remember me functionallity to be true when a user logs in.

@taylorotwell
Member

@digitalhuman followed those steps exactly and it works fine on my machine. There are also many Laravel 5.3 projects in production so I highly doubt that is some inherent problem with CSRF in Laravel 5.3.

Have you tried a different browser? A different computer?

@digitalhuman
digitalhuman commented Sep 26, 2016 edited

Yeah its totally unclear what the error causes. Also because there can be multiple reasons why this occurs. Like one of the issues could be the think @MountainDev is stating here:

https://laracasts.com/discuss/channels/laravel/53-tokenmismatchexception-in-laravels-auth-form

The other thing could be indeed Sessions are not written or stored at all. Server side caching could also interfere. I remember having similar issues in 5.0.

I just managed to solve my issue though. Really painfull to disclose it but ok. Here we go;

  1. Default cookie encryption was disabled (I really wounder why but that is another discussion @GrahamCampbell @taylorotwell ). So I enabled it.
  2. My .env file had a different domainname in it. Obviously then it gets ........!#$#@!!$$#@
    Solution: Make sure APP_URL matched the url of your dev environment. In my case: http://localhost, in some cased: http://localhost.dev etc etc etc

Good luck. Maybe we could combine the solutions?

/hides in the corner

@taylorotwell
Member
taylorotwell commented Sep 26, 2016 edited

What do you mean by default cookie encryption was disabled? You disabled it?

@digitalhuman
digitalhuman commented Sep 26, 2016 edited

@taylorotwell Nope it was default disabled. I enabled it.

https://snag.gy/7r3GCp.jpg

@oitsem099

guys I just tested it on XAMPP Environment.
fresh installation of 5.3 is running okay..

the bug is occurring on my Laragon Environment.
I'll try to update my Laragon and clear some cache and cookies.
to see if it works.

@digitalhuman
digitalhuman commented Sep 27, 2016 edited

@oitsem099 I guess you now know the checks you need to do right?

  1. Check if a session is generated, stored and valid
  2. Check for correct directory and file permissions
  3. Check for correct APP_URL in .env
  4. Debug with unencrypted cookies/sessions could also help.
  5. Check session domain equals APP_URL domain
@oitsem099

lol all I did was delete the current project.
cleared my cache and cookies.
installed a fresh 5.3 and restarted my Laragon Environment.
now its working..that's really weird.
I still have the same settings like before.

@milkandteamedia
milkandteamedia commented Sep 27, 2016 edited

A quick follow up to this issue....
I'm using, Vagrant and VirtualBox on macOS Sierra and Chrome.
Using the Laravel 5.3 install guide, and a fresh install the Auth - Register / Logon work fine.
Why I was searching the google's for the "VerifyCsrfToken.php" error because previously. I had set up a Vagrant, VirtualBox virtual machine and 'copied' my website files into the virtual machine using a file sync method, one by one, but sometimes whole folders.

I believe the problem is with encoding. I found that a lot of files were just broken. Extra characters, weird line wraps etc.

Like, @taylorotwell said in a reply to @digitalhuman
@digitalhuman followed those steps exactly and it works fine on my machine. There are also many Laravel 5.3 projects in production so I highly doubt that is some inherent problem with CSRF in Laravel 5.3.

Fresh installs work, because they're installed or created on one single machine, but a few of us have altered the files by moving, copying etc...

I don't have a fix, but it does work if someone else wants to try some of the deep core files... I open a file that is causing me trouble ... copy the text into a plan text editor in UTF-8, delete the file, and then make a new file, copy/paste it back ... save. It works.

just my 2 cents.

@digitalhuman

@milkandteamedia Yeah I gues those steps are kinda it. If we need to add more then please let me know. I will edit that post. I guess that is the fix.
I had the same issue because I copied my .env file from another project. Changed the key and DB user but forgot to change the APP_URL :) then everything gets $@##RF%^@#

@milkandteamedia

@digitalhuman In addition to moving/copying files from my local OS into a vagrant / VirtualBox sync folder they were once merged from GitHub ...
Again I don't have a fix or solution I just wanted to add my experience to this thread.
Copying and Pasting fresh text into fresh files is a mind numbing procedure, I started over with a fresh install and everything is working...

@nticaric
nticaric commented Oct 3, 2016

For reference, I just had this issue and after adding APP_URL to my .env the error was gone

@jasonmccreary
Contributor
jasonmccreary commented Oct 4, 2016 edited

I temporarily had this issue as well. It seems to occur when APP_URL and SESSION_DOMAIN are not inline with one another.

It also occurred when my Session Cookie Name (config/session.php) had a dot (e.g. jason.pureconcepts.net).

@cyberhicham

@jasonmccreary : Same behaviour here, once the APP_URL & SESSION_DOMAIN are the same, the tokenmismatch exception disappeared

@geodeveloper
Contributor

Tip: If you use the file driver for sessions check that storage folder it's writable and the web server user has access to read-write. TokenMismatchException is thrown if the CSRF token is not found in session (which is stored on storage/framework/sessions folder).

@goesredy
goesredy commented Oct 6, 2016

In my case, after the APP_URL & SESSION_DOMAIN are the same (added manually), the tokenmismatch exception just appeared sometimes. Another problem comes, logout function not working.
After click logout it will redirect to root, but the session still in there. So after click Login, will redirected to home, not to login form.

@digitalhuman

@goesredy Did you validate if an actual session is really created in either a DB or Redis or File? Sounds like some IO issue to me.

@goesredy
goesredy commented Oct 6, 2016 edited

@digitalhuman Yap, got it, sorry. Issues on mine. But still need to set SESSION_DOMAIN to make it worked.

@subin7
subin7 commented Oct 28, 2016

This is not a bug. Just clear localhost cookies on your browser every time you need to switch to other laravel projects.

@digitlimit
digitlimit commented Nov 2, 2016 edited

I encountered same problem but I was able to resolve it by ensuring the following keys in .env are correct

  APP_URL=http://mylocalsite.dev
  SESSION_DOMAIN=mylocalsite.dev
@digitalhuman

@digitlimit Exactly. Good point. Added 'session' part to the list above.

@et4m1r
et4m1r commented Nov 16, 2016

same problem here. why closed this issue.
i tried all default installation. but still showing "TokenMismatchException in VerifyCsrfToken.php line 68:"

@ttimot24
ttimot24 commented Nov 28, 2016 edited

Okey suddenly I got this error too. But only in one route. I'm trieing to solve this about 3 days. I googled everything and tried what others wrote but nothing works. Laravel creates a new session everytime I load the page and the datas I stored in session are lost. Any suggestion?

@digitalhuman
@ttimot24

Permissions are OK. Encrypt enabled. app_url and session_domain are the same. Session is generated. But the session token and the token that the form sends not the same.

@milkandteamedia

@ttimot24 What is your Environment like? Are you using Shared hosting, dev'ing locally? Are you using Vagrant or Virtual Box? I'm on the side that, moving files from local desktop environments to github and back etc might be the issue.

@digitalhuman

@ttimot24 Yeah that is exactly what I expect it to do. I really would like to know what your environment is like and where you develop on. Did you try settings session to 'file' and see if the form works after that?
Another option is to check if that /url/ is begin cached or not. I had some unexpected behaviour with that as well.

@ttimot24

I found the problem, there was a Session:flush() in one of my middleware. Thanks for the help! :)

@mairesweb

I found the solution by giving permission on the storage folder.

@keebeegee

switched to db session management as described here:
http://stackoverflow.com/questions/30338518/persisting-sessions-across-subdomains-in-laravel-5/39741256#39741256

I suppose in my case the issue was related to file permissions.

@NatLuder

Hello everyone,

I am trying to figure this issue out aswell, but I am experiencing some troubles...
So far I have tried:

  • The .env APP_URL and SESSION_DOMAIN (once exactly the same name "http://dev.project", once APP_URL "http://dev.project" and SESSION_DOMAIN "dev.project").

  • I have tried the thing where <!-- CSRF Token --> <meta name="csrf-token" content="{{ csrf_token() }}"> is only in the app.blade.php and nowhere else, then when it's only in the files with a form...

  • File permissions are given to storage dir, SESSION_DRIVER is set to 'file'.

  • Copy my files to a complete new setup...

  • Emptied my cache, deleted sessions and then logged back in

Login and register forms work without any problems. It's just my custom form (which only can be accessed when logged in) which won't work (with and without csrf token).
TokenMismatchException in VerifyCsrfToken.php line 68:

How can I check the other points about the session? I am still very new to Laravel 5.3, so I am sorry if I don't know how to check the session values.

My workstation:
I am working on a Mac OS Sierra 10.12.2 with PHPStorm and Laravel 5.3, VueJS and Bulma (no Bootstrap). My local server works with MAMP.

@Zedonboy
Zedonboy commented Jan 1, 2017

Hey happy new year everyone.
have got same problem too
Its funny that i cant see any
permissions, encryption property,
SESSION_DOMAIN in .env file

i use laravel 5.3.22 with xampp

@Zedonboy
Zedonboy commented Jan 1, 2017

i dont know my. env file is different or what?

@Zedonboy
Zedonboy commented Jan 1, 2017

@Natluder i have solved mine.. ........
sometimes when we code we make silly mistakes........Go to your html form that is either the sign up or register form in the form tag add {{csrf_field()}} in it

@Zedonboy
Zedonboy commented Jan 1, 2017

i pray this helps you

@NatLuder
NatLuder commented Jan 2, 2017

@Zedonboy Happy new Year to you too!

As I said before, register and login work. I am using this form of linking my CSRF token anyway, so I already have this. But I also tried it the other way with a hard coded CSRF token in a hidden input.

@Zedonboy
Zedonboy commented Jan 2, 2017

@Natluder are you using scalfolded auth in laravel for your login and Registration?. .....
if not i would love to see your code

@Zedonboy
Zedonboy commented Jan 2, 2017

honestly most of the time such errors comes from the form itself.. ....... for me

@NatLuder
NatLuder commented Jan 2, 2017

@Zedonboy I have used php artisan make:auth as always...

My custom form for creating a project looks like this:

<form role="form" method="POST" action="http://dev.project/create" class="control is-horizontal">
{{ csrf_field() }}
<div class="addmenu">
<div class="control is-horizontal">
<div class="control-label">
<label class="label">Name</label>
</div>
<div class="control is-fullwidth">
<input id="name" type="text" name="name" required="required" autofocus="autofocus" class="input">
</div>
</div>
<div class="control is-horizontal">
<div class="control-label">
<label class="label">Description</label>
</div>
<div class="control is-fullwidth">
<textarea id="description" name="description" rows="4" class="textarea"></textarea>
</div>
</div>
</div>
<div class="control is-horizontal btn-pull-right">
<button type="submit" class="button is-primary">
<span class="icon"><i class="fa fa-plus-square"></i></span>
<span>Create</span>
</button>
</div>
</div>
</form>

Usually I copy & paste forms from project to project (the base tags). So I don't really get why this should be wrong while all others work...

The web.php Route is as follows:
Route::post('/add', 'ProjectController@create');

And the Controller function ProjectController create:

public function create(Request $request) { if ($request->input('name') !== null && $request->input('description') !== null) { $event = new Event(); $event->name = $request->input('name'); $event->description = $request->input('description'); $user = Auth::user(); if($user) $event->user_id = $user->id; $event->save(); } return self::index(); }

@Zedonboy
Zedonboy commented Jan 2, 2017

well have printed your request in json format and _token is the same.
everything seems ok in my machine .

@Zedonboy
Zedonboy commented Jan 2, 2017

What sort of bug is this?

@Zedonboy
Zedonboy commented Jan 2, 2017

@Natluder remove the X-CSRF-TOKEN at the hearder

@Zedonboy
Zedonboy commented Jan 2, 2017

coz am trying to read the code of VerifyCsrfToken. php@handle function....
check whether your app match to 4 conditions...............#NOTHING WAS EASY EVEN PROGRAMMING

@Zedonboy
Zedonboy commented Jan 2, 2017

@Natluder from what am analyzing here.....VerifyCsrfToken@tokenmatch function, $sessionToken and $token.. ......may not be equal

@Zedonboy
Zedonboy commented Jan 2, 2017

Logically i suggest do something to the $sessionToken by.....maybe flush your sessions, cache , refresh your browser.. .....to initialize the $sessionToken.. ..

@NatLuder
NatLuder commented Jan 4, 2017 edited

@Zedonboy, It's getting weirder... I flush my session now at logout (via "/logout" route). I cleared my cache via php artisan cache:clear.
Now when I login, go to a different page I directly get logged out again. I think something is completely wrong here, but I do not get what it is. Also I created three times a new project, php artisan make:auth, copied parts of my project (very basics like welcome.blade.php and style.css) and it's the same...

@Zedonboy
Zedonboy commented Jan 4, 2017

@Natluder this is really a fluke not a bug
for the fact you have tried in many fresh project...... i guess its from you.. .. Aiit lets try unconventional means

  1. try changing your form action to just "create" dont put any http//dev.project
  2. try the using the most simplest form no css just {{csrf_token()}} <input.......bla.. bla.. > .......to check the bug
    3.disable the CSRFTOKEN middleware for the meantime

try each step before proceeding to the next

@artus9033

Sometimes getting same error. Tried changing the session driver to database, but didn't help. So, finally, is there any fix?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment