Reputation: 6081
I have a problem that seems to be reoccuring in Laravel but I can't fix it. When trying to login with my form I'm getting the Exception
TokenMismatchException in VerifyCsrfToken.php line 67:
My tokens are
57APQblkHvu9zZAMEdLYqQ1EwhPgZZtv4xEAYqmG // Request
byHXGzrMeMQGPtIBWo6FCgdKyXl2GkiekQk8IEND // Session
But why are they different? My login form looks like this and is the only HTML code on the view.
<form method="post" action="{{ route('login.do') }}">
<input type="submit" value="Login with Spotify">
{{ csrf_field() }}
</form>
What I tried
Using <input type="hidden" name="_token" value="{{ csrf_token() }}">
instead of the field.
Using {!! csrf_field() !!}
instead of {{ csrf_field() }}
Grouping all my routes into the web
middleware
<?php
Route::group(['middleware' => ['web']], function () {
Route::get(
'/',
[
'as' => 'start',
'uses' => 'HomeController@index'
]
);
Route::get(
'/login',
[
'as' => 'login.show',
'uses' => 'AuthenticationController@login'
]
);
Route::post(
'/login',
[
'as' => 'login.do',
'uses' => 'AuthenticationController@doLogin'
]
);
});
But as soon as I'm on login.blade.php
(GET Request) and then press submit to login I'm getting the above exception.
Upvotes: 2
Views: 132
Reputation: 11
the reasons behind 'TokenMismatchException in VerifyCsrfToken.php line 67:' can be quite complex. An understanding of the middleware involved is necessary. The diagram below shows the important details.Laravel Middleware for token(cookie) verification Diagram
Every request traverses both the StartSession and the VerifyXsrfToken layers. These manage a cookie named 'laravel_session' and 'XSRF_token' respectively. They are checked in this order and both are vital. If either of the cookies fail verification then the 'TokenMismatchException' is thrown. more details at Full details of Laravel middleware re TokenMismatchException in VerifyCsrfToken
Upvotes: 0
Reputation: 162
you need to put your "Route::post('/login', ...... " in ['middleware' => ['guest']] and not in ['middleware' => ['web']]
Keep all your "before login activities" outside ['middleware' => ['web']] group, since ['middleware' => ['web']] carries out sessions, cookies and csrf,etc. stuff which needs to be handled after user logins to you laravel web-app
Upvotes: 1