Laravel 5.4: TokenMismatchException [duplicate] - php

I know that this is a known error with things like forms in Laravel. But I am facing an issue with basic authentication in Laravel 5.2.
I created the auth using Laravel;
php artisan make:auth
Now I have the same copy of code on my server and my local. On my local I am getting no issue whatsoever. However on my server, when I try to register a user I get the error saying TokenMismatchException in VerifyCsrfToken.php Line 67
Both my local and server environments are in sync, yet I keep getting the error on registration. Any help on how I can fix this?

I'm assuming you added $this->middleware('auth'); inside the constructor of your controller to get the authentication working. In your login/register forms, if you are using {!! Form::someElement !!}, add the following line at the top as well:
{!! csrf_field() !!}
Or if you are using input tags inside your forms, just add the following line after <form> tag:
<input type="hidden" name="_token" value="{{ csrf_token() }}">
Hope this helps.

I had a similar issue and it was an easy fix.
Add this in your HTML meta tag area :
<meta name="csrf-token" content="{{ csrf_token() }}">
Then under your JQuery reference, add this code :
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
If you are using the HTML form submit (not AJAX) then you need to put :
{{ csrf_field() }}
inside your form tags.

I was about to start pulling out my hair!
Please check your session cookie domain in session.php config. There is a domain option that has to match your environment and it's good practice to have this configurable with you .env file for development.
'domain' => env('COOKIE_DOMAIN', 'some-sensible-default.com'),

If nothing is working you can remove the CSRF security check by going to App/Http/Middleware/VerifyCsrfToken.php file and adding your routes to protected $excpt.
e.g. if i want to remove CSRF protection from all routes.
protected $except = [
'/*'
];
P.S although its a good practice to include CSRF protection.

You need to have this line of code in the section of your HTML document, you could do that by default , it won't do any harm:
<meta name="csrf-token" content="{{ csrf_token() }}" />
And in your form you need to add this hidden input field:
<input type="hidden" name="_token" value="{{ csrf_token() }}">
Thats it, worked for me.

I was facing the same issue with my application running on laravel 5.4
php artisan session:table
php artisan make:auth
php artisan migrate
.. and then following command works for me :)
chmod 777 storage/framework/sessions/
One more possibility of this issue, if you have set SESSION_DOMAIN (in .env) different than HOST_NAME
Happy coding

I have also faced the same issue and solved it later.
first of all execute the artisan command:
php artisan cache:clear
And after that restart the project.
Hope it will help.

Your form method is post. So open the Middleware/VerifyCsrfToken .php file , find the isReading() method and add 'POST' method in array.

There are lot of possibilities that can cause this problem.
let me mention one.
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.

By default session cookies will only be sent back to the server if the browser has a HTTPS connection. You can turn it off in your .env file (discouraged for production)
SESSION_SECURE_COOKIE=false
Or you can turn it off in config/session.php
'secure' => false,

I also get this error, but I was solved the problem. If you using php artisan serve add this code {{ csrf_field() }} under {!! Form::open() !!}
php artisan cache:clear
Clear cache & cookies browser
Using Private Browser (Mozilla) / Incognito Window (Chrome)
Open your form/page and then submit again guys
I hope this is solve your problem.

Make sure
{!! csrf_field() !!}
is added within your form in blade syntax.
or in simple form syntax
<input type="hidden" name="_token" value="{{ csrf_token() }}">
along with this,
make sure, in session.php (in config folder), following is set correctly.
'domain' => env('SESSION_DOMAIN', 'sample-project.com'),
or update the same in .env file like,
SESSION_DOMAIN=sample-project.com
In my case {!! csrf_field() !!} was added correctly but SESSION_DOMAIN was not configured correctly. After I changed it with correct value in my .env file, it worked.

change the session driver in session.php to file mine was set to array.

Can also occur if 'www-data' user has no access/write permissions
on the folder:
'laravel-project-folder'/storage/framework/sessions/

Below worked for me.
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">

Have you checked your hidden input field where the token is generated?
If it is null then your token is not returned by csrf_token function.You have to write your route that renders the form inside the middleware group provide by laravel as follows:
Route::group(['middleware' => 'web'], function () {
Route::get('/', function () {
return view('welcome');
});
Here root route contains my sign up page which requires csrf token. This token is managed by laravel 5.2.7 inside 'web' middleware in kernel.php.
Do not forget to insert {!! csrf_field() !!} inside the form..

Go to app/provides.
Then, in file RouteServiceProvider.php, you'll have to delete 'middleware' => 'web' in protected function mapWebRoutes(Router $router)

The problem by me was to small post_max_size value in php.ini.

Put this code in between <form> and </form> tag:
<input type="hidden" name="_token" value="{{ csrf_token() }}">

I had the same issue but I solved it by correcting my form open as shown below :
{!!Form::open(['url'=>route('auth.login-post'),'class'=>'form-horizontal'])!!}
If this doesn't solve your problem, can you please show how you opened the form ?

You should try this.
Add {{ csrf_field() }} just after your form opening tag like so.
<form method="POST" action="/your/{{ $action_id }}">
{{ csrf_field() }}

Are you redirecting it back after the post ? I had this issue and I was able to solve it by returning the same view instead of using the Redirect::back().
Use this return view()->with(), instead of Redirect::back().

For me, I had to use secure https rather than http.

try changing the session lifetime on config/session.php like this :
'lifetime' => 120, to 'lifetime' => 360,
Here I set lifetime to 360, hope this help.

I got this error when uploading large files (videos). Form worked fine, no mismatch error, but as soon as someone attached a large video file it would throw this token error. Adjusting the maximum allowable file size and increasing the processing time solved this problem for me. Not sure why Laravel throws this error in this case, but here's one more potential solution for you.
Here's a StackOverflow answer that goes into more detail about how to go about solving the large file upload issue.
PHP change the maximum upload file size

In my case, I had a problem when trying to login after restarting server, but I had csrf field in the form and I didn't refresh the page, or it kept something wrong in the cache.
This was my solution. I put this piece of code in \App\Http\Middleware\VerifyCsrfToken.php
public function handle($request, Closure $next)
{
try {
return parent::handle($request, $next); // TODO: Change the autogenerated stub
} catch(TokenMismatchException $e) {
return redirect()->back();
}
}
What it does is catching the TokenMismatchException and then redirecting the user back to the page (to reload csrf token in header and in the field).
It might not work always, but it worked for my problem.

Try php artisan cache:clear or manually delete storage cache from server.

If you check some of the default forms from Laravel 5.4 you fill find how this is done:
<form class="form-horizontal" role="form" method="POST" action="{{ route('password.email') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required> #if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span> #endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Send Password Reset Link
</button>
</div>
</div>
</form>
{{ csrf_field() }}
is the most appropriate way to add a custom hidden field that Laravel will understand.
csrf_filed() uses csrf_token() inside as you can see:
if (! function_exists('csrf_field')) {
/**
* Generate a CSRF token form field.
*
* #return \Illuminate\Support\HtmlString
*/
function csrf_field()
{
return new HtmlString('<input type="hidden" name="_token" value="'.csrf_token().'">');
}
}
And csrf_field() method uses session for the job.
function csrf_token()
{
$session = app('session');
if (isset($session)) {
return $session->token();
}
throw new RuntimeException('Application session store not set.');
}

I have same issue when I was trying out Laravel 5.2 at first, then I learnt about {{!! csrf_field() !!}} to be added in the form and that solved it. But later I learnt about Form Helpers, this takes care of CSRF protection and does not give any errors. Though Form Helpers are not legitimately available after Laravel 5.2, you can still use them from LaravelCollective.

Got to your laravel folder :: App/http/Middleware/VerifyCsrfToken.php
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
// Pass your URI here. example ::
'/employer/registration'
];
}
And it will exclude this url from the Csrf validation. Works for me.

Related

Laravel error TokenMismatchException&

I try to register user(using angular js).This is my form:register.blade.php
<div class="panel-footer" id="free-panel-footer">
<form
name="registerCtrl.registerForm"
ng-submit="registerCtrl.submit(registerCtrl.registerForm.$valid)"
novalidate
class="register-form"
autocomplete="off">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
....
In head index file i put this:
<meta name="csrf-token" content="{!! csrf_token() !!}">
but i got error TokenMismatchException in compiled.php line 2927&?
Try replacing that hidden input you wrote manually with {!! csrf_field() !!}. That will print the token for you and you'll be sure it's the correct name and value.
Since you are not submitting the form in a default GET or POST request, you need to add that field manually to the AJAX call you're doing, and you can use that generated field to gather the name and the value of the csrf-token. You will need to do something like this for your javascript.
Just in case nothing of this works, and under your own responsability for the security hole you will create, you can exclude that concrete route from needing the csrf-token on app/Http/Middleware/VerifyCsrfToken middleware, adding the path to the $except array.

laravel 5.5 The page has expired due to inactivity. Please refresh and try again

I'm new with Laravel and I have a problem which I don't understand.
I have а log form in my project and my method is POST. When I try a request the result is:
'The page has expired due to inactivity. Please refresh and try
again.'
But if I change the method to GET, It works fine.
Can someone tell me why is that and how to fix it? because of course I need POST method.
This problem comes from the CSRF token verification which fails. So either you're not posting one or you're posting an incorrect one.
The reason it works for GET is that for a GET route in Laravel, there is no CSRF token posted.
You can either post a CSRF token in your form by calling:
{{ csrf_field() }}
Or exclude your route (NOT RECOMMENDED DUE TO SECURITY) in app/Http/Middleware/VerifyCsrfToken.php:
protected $except = [
'your/route'
];
In my case, I've got the same error message and then figured out that I've missed to add csrf_token for the form field. Then add the csrf_token.
Using form helper that will be,
{{ csrf_field() }}
Or without form helper that will be,
<input type="hidden" name="_token" value="{{ csrf_token() }}">
If that doesn't work, then-
Refresh the browser cache
and now it might work, thanks.
Update For Laravel 5.6
Laravel integrates new #csrf instead of {{ csrf_field() }}. That looks more nice now.
<form action="">
#csrf
...
</form>
Anytime you define an HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware can validate the request. You may use the csrf_field helper to generate the token field:
<form method="POST" action="/profile">
{{ csrf_field() }}
...
</form>
It doesn't work, then Refresh the browser cache and now it might work,
For more details open link :- CSRF Protection in Laravel 5.5
UPDATE:
With Laravel 5.6 using Blades templates, it's pretty easy.
<form method="POST" action="/profile">
#csrf
...
</form>
For more details open link :- CSRF Protection in Laravel 5.6
Verify that your config/session.php file contains this line
'domain' => env('SESSION_DOMAIN', null),
Then remove the SESSION_DOMAIN line in your .env file
In my case , I added ob_start(); at the top of my index.php on server and everything seems to be working fine.
Excluding URIs From CSRF Protection:
Sometimes you may wish to exclude a set of URIs from CSRF protection. For example, if you are using Stripe to process payments and are utilizing their webhook system, you will need to exclude your Stripe webhook handler route from CSRF protection since Stripe will not know what CSRF token to send to your routes.
Typically, you should place these kinds of routes outside of the web middleware group that the RouteServiceProvider applies to all routes in the routes/web.php file. However, you may also exclude the routes by adding their URIs to the $except property of the VerifyCsrfToken middleware:
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'stripe/*',
'http://example.com/foo/bar',
'http://example.com/foo/*',
];
}
i had same problem. use 'clear browsing data' in chrome. maybe solve your problem.
This happens because you are using the default CSRV middleware from Laravel's installation. To solve, remove this line from your Kernel.php:
\App\Http\Middleware\VerifyCsrfToken::class,
This is fine if you are build an API. However, if you are building a website this is a security verification, so be aware of its risks.
Tried different solutions to solve the problem for several weeks without success.
The problem I was facing was caused by upgrading from laravel 5.0 to 5.5 and forgot to update config/session.php
If anyone is facing the problem, try to update the config/session.php to match the version on Laravel you are running
I had the same problem, I have tried many solutions. but none worked for me. then I found out that for some reason I was using this in my .env file:
SESSION_DOMAIN= myapp.me
and as soon as I put it back to null, everything worked just fine.
Place {{csrf_field()}} Into your form tag
First, include csrf in your form.
{{ csrf_field() }}
if the problem didn't solve, then use ob_start(); at the very start of index.php.
<?php ob_start();
If you have already included the CSRF token in your form. Then you are getting the error page possibly because of cache data in your form.
Open your terminal/command prompt and run these commands in your project root.
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear,
Also try to clear the browser cache along with running these commands.
if your config is set: SESSION_DRIVER=file you have to check if your session directory is writable. Check storage/framework/session
In my case, there was 'space' before <?php in one of my config file.
This solved my issue.
Just place this code inside the form
<input type = "hidden" name = "_token" value = "<?php echo csrf_token() ?>" />
I was facing the same error so i just removed this line from my .env file
SESSION_DRIVER=yourwebsite.com
Still anyone have this problem, use following code inside your form as below.
echo '<input type = "hidden" name = "_token" value = "'. csrf_token().'" >';
Just add #csrf inside your form tag.
Or you can include csrf_token in the header to send it with every request.
if you need to change form action with Javascript you will have the same problem
1.first you need to use instead of {!!Form::open() !!} {!! close() !!} in laravel
2.second you most begin your action with https://www.example.com +your Route
Do not Forget www in your url!!!
In my case the same problem was caused because I forgot to add > at the end of my hidden input field, like so: <input type="hidden" name="_token" value="{{ Session::token() }}"
So, I fixed it by adding it:
<input type="hidden" name="_token" value="{{ Session::token() }}">
It's Funny but it works for me. i realised this is Caused because of default HTML TAG in laravel code.
Use /* */ or {{-- --}} instead
Or Try to Remove Recently Html Coment in you code...
Or change Html Comment to Php Comment...
Or try to run Any Worng artisan command like php artisan clean browser And See if it output any HTML Commented data along with it error...
We got it working by copying the routes from Router.php instead of using Auth::routes(), these are the routes you need:
Route::get('login', 'Auth\LoginController#showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController#login');
Route::post('logout', 'Auth\LoginController#logout')->name('logout');
// Registration Routes...
Route::get('register', 'Auth\RegisterController#showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController#register');
// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController#showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController#sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController#showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController#reset');
I know this question has been satisfactorily answered, but I wanted to mention a fix that worked in my case. I added {{ csrf_field() }} and it still didn't work.
Then I remembered that I blocked all cookies for development purposes, which can be nice when you change the page and want to refresh it.
Once I changed the settings to stop blocking all cookies in MS Edge browser the problem went away.
my problem solved by just adding #csrf in form tag
Laravel 5.6 doesn't support {{ csrf_field() }} just add #csrf in place of {{ csrf_field() }}
larvel_fix_error.png
It may be csrf token do not have in your form. You have to use #crsf or {{ csrf_field() }}
If you are use csrf on your form. It may be cache. Clear your app cache.
php artisan cache:clear
php artisan view:clear
php artisan cache:clear
And clear your browser cache.
If errors again show you, then create a new key
php artisan key:generate
If anyone still looking for an answer to this issue. For me it happens when I'm switching between local and production server and I'm logged on both sites. To fix the issue, just clear the session.
just set the 'expire_on_close' => true in config\session.php and restart your browser
I recently went through this problem, tried all the solutions proposed here (and the internet) without success for 5 days.
In my case my environment:
Laravel: 5.5
PHP: 7.2
SSL: production
Apache
CENTOS
The problem is that I had automated the deployment using the git --bare repository with ansimble.
And all folders when pushing were with permission 0775 (inherited from the git user). When ansinble was run it replicated this permission to all folders. When composing install for example, all vendor folders also had this permission.
The csrf, has a policy of blocking what is considered insecure, especially if you use an encrypted environment (SSL).
I only realized the problem when I decided to carry out the deployment manually, zipped the project, uploaded it, unzipped it and ran the commands to generate the caches and dependencies. And then I realized that this way all folders were with permission 0755 (inherited from the system user). And this is the default permission that is considered safe.
In my case, it seems to be an issue in my web browser (Firefox for Android) or my smartphone with full storage. In another browsers and devices it works. By the way, the issue happens only when I send files through the form, I realized I currently can't upload files from my smartphone through this browser in any websites like https://filebin.net.
This is very simple for me. maybe the sessions folder is missing in storage/framework/sessions

Laravel login TokenMismatchException in VerifyCsrfToken.php line 46

I know this question has been asked many times and I've tried everyone of them to fix my issue:
I use Laravel auth/login to login to my admin section. It's all worked perfectly well until recently when I added some new routes/views to this section. Now when I try to login, I get the TokenMismatchException in VerifyCsrfToken.php line 46 error.
I have tried php artisan key:generate and I also have the line <input type="hidden" name="_token" value="{{ csrf_token() }}" /> in my form.
This is my routing for the login:
Route::get('auth/register', function() { return redirect('/'); });
//stops anyone registering
Route::get('admin','AdminPagesController#adminHome');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
I've scratched my head and I simply don't understand what the issue is and I'm hoping someone can help.
I'm using Laravel 5
Add this to the form instead of the hidden field:
{{ csrf_field() }}
Anytime you define a HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware can validate the request. You may use the csrf_field helper to generate the token field
https://laravel.com/docs/5.4/csrf#csrf-x-csrf-token
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
to
{{ csrf_field() }}
if you are using ajax requests you have to set that :
1- <meta name="csrf-token" content="{{ csrf_token() }}"> in <head></head> section
2-
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
see https://laravel.com/docs/5.4/csrf#csrf-x-csrf-token

Laravel 5 TokenMismatchException in VerifyCsrfToken.php line 46

EDIT: i get this error even for public/auth/login after pushing the Login button
Hi i'm simply trying to output a Session::flash() but I get this error message:
TokenMismatchException in VerifyCsrfToken.php line 46
Here is the code:
public function update($id, Requests\EditPostRequest $request)
{
$post = Post::findOrFail($id);
$post->update($request->all());
return redirect(route('news.edit', $id))->with('success', 'Operation successful !');
}
And this is in my view:
#if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
</div>
#endif
I really need to fix that :/
Just add {{ Form::token() }} before the closing tag of your form.
It appears to be related to using the same key in both your local/dev environment and production one.
I'm not sure how you'd get collisions, though, given that the sessions should be independent of environment, but I was doing some local development earlier. Everything was working fine in dev, pushed my project to my other PC and than I hit the TokenMismatchException.
I had a poke around my .env file and sure enough, the keys were the same between my two environments. Changing the key in my prod environment and the TokenMismatchException went away straight away.
Just look at your token which get set if they are the same change the production key with php artisan key:generate , hope for you this will work, just let me know if it don't.
Do you have a CSRF token in your form?
<form method="post" action="someaction">
{{ csrf_field() }} // Generates an input field with a token
// Other input fields
</form>

The CSRF token is invalid. Please try to resubmit the form

I'm getting this error message every time I try to submit the form:
The CSRF token is invalid. Please try to resubmit the form
My form code is this:
<form novalidate action="{{path('signup_index')}}" method="post" {{form_enctype(form)}} role="form" class="form-horizontal">
<div class="form-group">
{{ form_label(form.email, 'Email', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
{{ form_widget(form.email, {'attr': {'class': 'col-md-2'}}) }}
{{ form_errors(form.email) }}
</div>
<div class="form-group">
{{ form_label(form.nickname, 'Nickname', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
{{ form_widget(form.nickname, {'attr':{'class': 'col-md-2'}}) }}
{{ form_errors(form.nickname, {'attr': {'class': 'col-md-3'}}) }}
</div>
<div class="form-group">
{{ form_label(form.password, 'password', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
{{ form_widget(form.password, {'attr': {'class': 'col-md-2'}}) }}
{{ form_errors(form.password, {'attr': {'class': 'col-md-3'}}) }}
</div>
<div class="form-group">
{{ form_label(form.password_repeat, 'Repeat password', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
{{ form_widget(form.password_repeat, {'attr':{'class': 'col-md-2'}}) }}
{{ form_errors(form.password_repeat, {'attr': {'class': 'col-md-3'}}) }}
</div>
<div class="form-group">
<div class="col-md-1 control-label">
<input type="submit" value="submit">
</div>
</div>
</form>
Any ideas?
You need to add the _token in your form i.e
{{ form_row(form._token) }}
As of now your form is missing the CSRF token field. If you use the twig form functions to render your form like form(form) this will automatically render the CSRF token field for you, but your code shows you are rendering your form with raw HTML like <form></form>, so you have to manually render the field.
Or, simply add {{ form_rest(form) }} before the closing tag of the form.
According to docs
This renders all fields that have not yet been rendered for the given
form. It's a good idea to always have this somewhere inside your form
as it'll render hidden fields for you and make any fields you forgot
to render more obvious (since it'll render the field for you).
form_rest(view, variables)
Also you can see this error message when your form has a lot of elements.
This option in php.ini cause of problem
; How many GET/POST/COOKIE input variables may be accepted
max_input_vars = 1000
Problem is that _token field misses PUT (GET) request, so you have to increase value.
Also, it concerns a big files. Increasing the
upload_max_filesize
option will solve problem.
This happens because forms by default contain CSRF protection, which is not necessary in some cases.
You can disable this CSRF protection in your form class in getDefaultOptions method like this:
// Other methods omitted
public function getDefaultOptions(array $options)
{
return array(
'csrf_protection' => false,
// Rest of options omitted
);
}
If you don't want to disable CSRF protection, then you need to render the CSRF protecion field in your form. It can be done by using {{ form_rest(form) }} in your view file, like this:
<form novalidate action="{{path('signup_index')}}" method="post" {{form_enctype(form)}} role="form" class="form-horizontal">
<!-- Code omitted -->
<div class="form-group">
<div class="col-md-1 control-label">
<input type="submit" value="submit">
</div>
</div>
{{ form_rest(form) }}
</form>
{{ form_rest(form) }} renders all fields which you haven't entered manually.
Before your </form> tag put:
{{ form_rest(form) }}
It will automatically insert other important (hidden) inputs.
I had this issue with a weird behavior: clearing the browser cache didn't fix it but clearing the cookies (that is, the PHP session ID cookie) did solve the issue.
This has to be done after you have checked all other answers, including verifying you do have the token in a hidden form input field.
In addition to others' suggestions you can get CSRF token errors if your session storage is not working.
In a recent case a colleague of mine changed 'session_prefix' to a value that had a space in it.
session_prefix: 'My Website'
This broke session storage, which in turn meant my form could not obtain the CSRF token from the session.
If you have converted your form from plain HTML to twig, be sure you didn't miss deleting a closing </form> tag. Silly mistake, but as I discovered it's a possible cause for this problem.
When I got this error, I couldn't figure it out at first. I'm using form_start() and form_end() to generate the form, so I shouldn't have to explicitly add the token with form_row(form._token), or use form_rest() to get it. It should have already been added automatically by form_end().
The problem was, the view I was working with was one that I had converted from plain HTML to twig, and I had missed deleting the closing </form> tag, so instead of :
{{ form_end(form) }}
I had:
</form>
{{ form_end(form) }}
That actually seems like something that might throw an error, but apparently it doesn't, so when form_end() outputs form_rest(), the form is already closed. The actual generated page source of the form was like this:
<form>
<!-- all my form fields... -->
</form>
<input type="hidden" id="item__token" name="item[_token]" value="SQAOs1xIAL8REI0evGMjOsatLbo6uDzqBjVFfyD0PE4" />
</form>
Obviously the solution is to delete the extra closing tag and maybe drink some more coffee.
I had this error recently. Turns out that my cookie settings were incorrect in config.yml. Adding the cookie_path and cookie_domain settings to framework.session fixed it.
I hade the same issue recently, and my case was something that's not mentioned here yet:
The problem was I was testing it on localhost domain. I'm not sure why exactly was this an issue, but it started to work after I added a host name alias for localhost into /etc/hosts like this:
127.0.0.1 foobar
There's probably something wrong with the session while using Apache and localhost as a domain. If anyone can elaborate in the comments I'd be happy to edit this answer to include more details.
In case you don't want to use form_row or form_rest and just want to access value of the _token in your twig template. Use the following:
<input type="hidden" name="form[_token]" value="{{ form._token.vars.value }}" />
In my case I got a trouble with the maxSize annotation in the entity, so I increased it from 2048 to 20048.
/**
* #Assert\File(
* maxSize = "20048k",
* mimeTypes = {"application/pdf", "application/x-pdf"},
* mimeTypesMessage = "Please upload a valid PDF"
* )
*/
private $file;
hope this answer helps!
I faced a similar issue. After ensuring the token field was actually rendered (see accepted answer) I checked my cookies.
There were 2(!) cookies for the domain in my Chrome browser, apparently because I was running the application on the same domain as another app, but with a different port (i.e. mydomain.com set the original cookie while the buggy app was running on mydomain.com:123)
Now apparently Chrome sent the wrong cookie so the CSRF protection was unable to link the token to the correct session.
Fix: clear all the cookies for the domain in question, make sure you don't run multiple applications on the same domain with differing ports.
I had the same error, but in my case the problem was that my application was using multiple first-level domains, while the cookie was using one. Removing cookie_domain: ".%domain%" from framework.session in the config.yml caused cookies to default to whatever domain the form was on, and that fixed the problem.
You need to remember that CSRF token is stored in the session, so this problem can also occur due to invalid session handling. If you're working on the localhost, check e.g. if session cookie domain is set correctly (in PHP it should be empty when on localhost).
This seems to be an issue when using bootstrap unless you are rendering the form by {{ form(form)}}. In addition, the issues seems to only occur on input type="hidden". If you inspect the page the with the form, you'll find that the hidden input is not part of the markup at all or it's being rendered but not submitted for some reason. As suggested above, adding {{form_rest(form)}} or wrapping the input like below should do the trick.
<div class="form-group">
<input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
</div>

Categories