31

Have just statred a new app in Laravel 5 and I am having some trouble using the out of the box auth...

I keep getting : TokenMismatchException in VerifyCsrfToken.php line 46: on submitting the login or signup forms...

I can see on the login form page the token codes that are in the hidden form field and Session at that point are the same...

As a test I have also tried as some other posts suggested commenting out //'App\Http\Middleware\VerifyCsrfToken', in app/Http/kernal.php to see what would happen. After doing this every time I submit a form I get a message which says redirecting to: /auth/login or /auth/register depending on where I came from with no success.

The weird thing was this was working when I first installed the framework. All I have done since then is run a few migrations and setup some of my models and controllers and seeded the db with some user data.

UPDATE:

Looking into this further in the function tokensMatch() on line 55 of VerifyCsrfToken.php if I :

var_dump($request->session()->token());

var_dump($request->input('_token'));

I can see the two tokens are different but at the form using:

var_dump(Session::all());

{{{ csrf_token() }}}

They are the same. The Session token has changed some how before it gets to the function tokensMatch() on line 55 of VerifyCsrfToken.php

My stack trace is as follows:

in VerifyCsrfToken.php line 46
at VerifyCsrfToken->handle(object(Request), object(Closure)) in VerifyCsrfToken.php line 17
at VerifyCsrfToken->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 55
at ShareErrorsFromSession->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 61
at StartSession->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 36
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 40
at EncryptCookies->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 42
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 101
at Pipeline->then(object(Closure)) in Kernel.php line 111
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 84
at Kernel->handle(object(Request)) in index.php line 53
trenthogan
  • 986
  • 1
  • 9
  • 14
  • IS this a standard form post or are you using ajax? – Chris Townsend Mar 05 '15 at 13:45
  • Standard form post. Just using the out of the box Laravel 5 auth setup. – trenthogan Mar 05 '15 at 18:22
  • Do you get a new file in `storage/frameworks/sessions` every time you refresh the page? – Marwelln Mar 05 '15 at 19:01
  • Yep a new file is been saved on every refresh... – trenthogan Mar 05 '15 at 21:25
  • 1
    I have fixed the problem by installing the framework again and copying across all my models, views, controllers, migration and seeding files and re added composer packages. Still not sure what the actual cause of the problem was but a fresh install and away I go again... I have kept the old codebase so if anyone has any ideas I am still keen to find an answer for anyone else facing the same problem.. – trenthogan Mar 07 '15 at 10:02
  • 1
    This can also happen if you land on a page that has a form that uses tokens, and don't submit the form for an extended amount of time, thus expiring the token, or, the clock on your computer is off. – Jesse Szypulski Mar 16 '15 at 03:58
  • This is shades of CodeIgniter. Having the same issue with Laravel 5 running PHP 5.6.9 giving 'TokenMismatchException VerifyCsrfToken.php on line 46' on every post request. L5 running PHP 5.4 no problem. Anybody know of a fix? I tried every suggestion here and at https://laracasts.com/discuss/channels/general-discussion/keep-getting-tokenmismatchexception-verifycsrftokenphp-on-line-46?page=2 including a full reinstall but no luck. – suncoastkid May 27 '15 at 17:03
  • 1
    Using PHP 7.1.7 and its built-in web server (`php artisan serve` => `php -S server.php`), and facing the same (or similar) issue. The cookie does not get to the script complete, it gets cut off most (but not all!) of the page requests. Found that out by logging the length of `$_SERVER['HTTP_COOKIE']`, and observing (using a proxy – "Fiddler") the actual cookie sent by the browser (which was all right). If it gets cut off in a form post request, the session loses the token, it gets re-generated and does not match the one passed in from the form. – Jānis Elmeris Aug 01 '17 at 12:40
  • 1
    So, it seems it's a problem at least partly caused by the web server, in my case it's the PHP's built-in server. However, I could not reproduce this with a simplified server that just outputs the received cookie and does nothing else – in this simple case it returned the cookie all right, even if it was exactly the same the Laravel's app had problems with. The work-around in my case was to not use any other apps on the same domain (I removed the Adminer's cookie part), thus decreasing the cookie by about 200 bytes (to 1050 bytes), and the server doesn't seem to have problems with this length. – Jānis Elmeris Aug 01 '17 at 12:46

19 Answers19

26

I first just got it working removing the line:

'Illuminate\Foundation\Http\Middleware\VerifyCsrfToken'

from /app/Http/Resquests/Kernel.php. However, this means the CSRF token check will be removed, which implies that your website will not be protected from cross-site request forgeries.

Update According to the documentation, you should add the CSRF token to your form by adding this snippet to your code:

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

I used first way in backend services for mobile application but I find I can send send CSRF header within requests.

Vince
  • 1,570
  • 3
  • 27
  • 48
Mahmoud Nassar
  • 609
  • 7
  • 16
11

According to documentation may be why:

Insert The CSRF Token Into A Form

<input type="hidden" name="_token" value="{{ csrf_token() }}">
Javier dc
  • 565
  • 6
  • 14
6

I had the same issue. I solved it by changing the following line in config/session.php

'domain' => env('DOMAIN', 'yourdomainnamehere.co.uk'),

Then add the following line in you .env

DOMAIN=null
Phoenix1331
  • 71
  • 1
  • 3
4

Check your routes.php file. I also had this error and it turned out to be caused by a blank line at the top (just before the opening <?php tag). Such a stupid error, hopefully this could help someone.

Myone
  • 1,103
  • 2
  • 11
  • 24
  • Lol, after a half day of researching and debugging, a blank line was the reason for a such stupid bug. Thank you! – valkirilov Mar 28 '17 at 06:38
3

I had the same problem, my solution was

<form method="POST" action="path_to_action">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <input type="text" name="some_name">
</form>
Xabir
  • 81
  • 1
  • 1
  • 5
  • Hi thanks mate! It solved my error . but I just wondering, should I put this `` at all my input form field for POST ? – Fai Zal Dong Apr 07 '17 at 11:49
  • Sorry for late reply, No you don't need to all your input form field for POST, you just need to put it once for every
    – Xabir Mar 19 '18 at 11:04
2

If you are using blade templates you can use put in your form

{{ csrf_field() }}

instead of

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

It worked with me in Laravel 5.1.

Organic Advocate
  • 919
  • 1
  • 15
  • 16
1

Just Log out and re login thats the only way It's a unknown bug even I get it in my form posting sometimes but all people in the forums they all say for putting but that does not solve the problem just logout and re-login

msonowal
  • 1,553
  • 3
  • 17
  • 36
  • This worked for me. Even though I thought I was already logged out, I did a force-logout (by visiting my logout URL) and problem solved. – mopo922 Jul 08 '15 at 03:08
1

If you want to get rid of TokenMismatchException in VerifyCsrfToken.php, check this link for simple solution by @Tariq Khan: TokenMismatchException in VerifyCsrfToken.php

Community
  • 1
  • 1
Chandz
  • 1,173
  • 3
  • 18
  • 34
1

I had the same issue, running php artisan config:cache

solved it all.

I hope this helps someone

0

I also had this very same situation today, out of the sudden my application started to show me that message...

I just re-started my server and it all went back to normal.

carlosbvz
  • 163
  • 2
  • 14
0

Solved the issue:

When I checked the app.blade csrf-token was hard coded there like <meta content="9DB/rSl5JKAkQenkfGLj4o/x6+1dIDC5m52IWJxjFfo=" name="csrf-token"> after removing this and adding <meta content="authenticity_token" name="csrf-param"> fixed my issue.

halfer
  • 19,824
  • 17
  • 99
  • 186
Kiren S
  • 3,037
  • 7
  • 41
  • 69
0

This is what I do to fix this issue.

Assume that your web server has already write access to session directory, in my case 'app/storage/framework/sessions/'.

Execute,

$ rm -f {your_web_app}/storage/framework/sessions/*

Reload web in your browser and try to login again.
0

There are lot of possibilities that can cause this problem. what I experience is that this can be a problem of wrong configuration of session.php config file. Have you by any chance altered your session.php config file? May be you have changed the value of domain from null to you site name or anything else in session.php

'domain' => null,

Wrong configuration in this file can cause this problem.

Yasir Ijaz
  • 674
  • 1
  • 12
  • 19
0

Try php artisan route:list and check id web middleware is repeated. For example (web,web,others).

In Laravel 5.3 web middleware is activated by default, I've added

Route::group(['middleware' => 'web'], function () { ALL MY ROUTE });

with this TokenMismatch was generated.

Fix routes solve the problem for me.

For more information see Question on Laracast

FilippoLcr
  • 119
  • 2
  • 10
0

If you want to use CSRF in form then you have to add this line in your form

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

and if you are not interested to use CSRF then you have to comment below line in kernel.php file

//\App\Http\Middleware\VerifyCsrfToken::class,
Eiko
  • 25,601
  • 15
  • 56
  • 71
0

Maybe its something with your App Domain settings.

  1. Check the 'domain' setting in config/session.php.
  2. Set it to 'localhost' or to the proper domain which is associated to your app.
  3. Save the file

Mine was fetched from the env file and the app was on a different domain.

Hope this is gonna save some brain cells for someone.

dcode
  • 1
0

Interestingly, I encounter the similar problem recently. I found there're two different tokens generated by my Laravel 5.1 app. I tackled the issue by generating a new application key [php artisan key:generate]!

Frank Liu
  • 11
  • 1
0

goto file called ... VrifyCsrfToken.php . located at app/Http/Middleware/

folder.

and change following....

namespace App\Http\Middleware;

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

class VerifyCsrfToken extends BaseVerifier {

protected $except = [
    "*" .   //make * here . as is did.
];

}

-1
<script>
function closedLogo() 
         {    
          $.ajax({
                  url: '{{route('core.closed-logo')}}',
                  type: 'post',
                  success: function (data) {
                      $('#return').html(data);
                  }
                 });
          }
</script>
Vimal
  • 1,140
  • 1
  • 12
  • 26