Laravel 5 TokenMismatchException in VerifyCsrfToken.php line 46 - php

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>

Related

Laravel POST failing - MethodNotAllowedHttpException (405) - even with POST Route and CSRF defined

I have a form with the method post set and the csrf_field() included:
<form method="post">
{{ csrf_field() }}
...
<button type="submit" class="btn btn-xs btn-space btn-primary">Save and finish</button>
</form>
Within my Routes, I have set everything up appropriately:
Route::get('/assess/{room_name}/{subject_selected}/{unit_selected}/{outcome_selected}', 'AssessmentHandler#step_6_assess');
Route::post('/assess//{room_name}/{subject_selected}/{unit_selected}/{outcome_selected}', 'AssessmentHandler#step_6_save');
The functions within the Controller are defined and everything should be working fine.
However, when I submit the form I am getting this error message:
Symfony \ Component \ HttpKernel \ Exception \
MethodNotAllowedHttpException No message
I have not seen this message before and am not sure where this is being triggered from in my particular instance. All of the search results I've read about this specific error talk about changing from GET to POST or ensuring CSRF protection is in place, but that isn't my issue here.
Using Dev tools, it is showing a 405 error (Method Not Allowed).
Any idea what might be happening here?
Try replacing {{ csrf_field() }} with #csrf.
You also have 2 slashes in the post url: Route::post('/assess//{room_name}
Make sure you are redirecting to the correct page.
Maybe you could show us the code in your controller.
Is your controller really AssessmentHandler and not AssesmentHandlerController?

Laravel 5.4: TokenMismatchException [duplicate]

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.

Laravel: MethodNotAllowedHttpException only on production server

I have read laravel throwing MethodNotAllowedHttpException and I know that this error often appears when one is POSTing to a GET route, but I am really sure that I am POSTing to a POST route.
Also this does work on my locale Homestead version but its not working on my apache production server.
There is nothing in the Laravel log file.
This is the error:
If one takes a closer look there is GET and POST, I am not sure if something is wrong with the request:
This is start of the from from the blade file (I am not using JS, its a pure HTML based form):
<form action='/users/update/' method='post' id='contactForm'>
{{ csrf_field() }}
<h2>
#lang('list.memb_4')
<input type="submit" class="savebutton" id='contactButton' value="#lang('list.default_41')"></h2>
Any suggestion what could cause this error?
I had to change
<form action='/users/update/' method='post' id='contactForm'>
to
<form action='/users/update' method='post' id='contactForm'>
In my web.php file I also use
Route::post('/users/update', 'UserController#update');
I don't know why - but on my test server Homestead this was no problem, but on my production server this is a problem.

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 5.4 "MethodNotAllowedHttpException" (Basic Task List)

i was trying to follow this tutorial on Laravel, even though most of the code & directories there were outdated, i managed to make the "Add Task" and also The Form to show up after a few errors.
now the problem, the delete button.
when i click on it, it shows a "MethodNotAllowedHttpException".
i changed the source code to match the newest version of Laravel.
my form (current version) :
<form action="{{ url('/task/'.$task->id) }}" method="POST">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<button type="submit" class="btn btn-danger">
<i class="fa fa-btn fa-trash"></i>Delete
</button>
</form>
my route :
Route::delete('/task/{id}', function ($id) {
Task::findOrFail($id)->delete();
return redirect('/');
});
i've been trying to fix this for 4 hours now, changing the methods of my route and form; but to no avail.
this is my first question on this site, sorry if there's something wrong in this question.
thanks~
edit:
to further help the effort, here's the complete error log
Error log, in Google Chrome
Change
<form action="{{ url('task/'.$task->id) }}" method="DELETE">
to
<form action="{{ url('task/'.$task->id) }}" method="POST">
Because form method DELETE does not exist, Laravel just "overwrites" this method with the hidden input "method" (you can place this input using "{{ method_field('DELETE') }}").
Form dosent support method Delete or Put ... It support only get and post methods, if You want implement delete in laravel this article will help you
link
Answer :
Turns out the problem lies in the Database-table itself, let me explain :
i was referring to a 'tasks' table that is referred as 'task' in code (no problem)
BUT, i was referring to a column called "ID" in my table as "id" in my code, creating the error (a rookie mistake).
thanks to #Autista_z for the pointer, and everyone else below for the guidance!

Categories