Laravel 5.2 TokenMisMatchException on Production Server - php

I am encountering TokenMismatchException on my Production Server, but the application working fine on local Xampp server and another hosting. It our in house server, so we cannot changed it. We have to use it, but we did not understand where is the issue.
Please friends help me, did i need to change anything in server like plugin, extensions or anything else, Please let me know. Here is screen shot below:
Above sceenshot is from Production and one of hosting provider. On production server laravel application giving tokenmismatchexception whereas same application working fine on another hosting provider. We did not understand why this is happening. Please suggest us what to do.
Update:
I have fresh laravel 5.2 and run php artisan make:auth after that i have given 777 permission to the folder, then donw nothing. Still i am getting this exception.

Add this in your html form
<input type="hidden" name="_token" id="_token" value="{{csrf_token()}}">
in blade
{!! Form::token() !!}
And add your route in web middwlware
Route::group(['middleware' => 'web'], function() {
// Place all your web routes here...
});

This is probably the sessions that are not being set properly.
Try to delete your PHP_SESSID cookie or change the way the sessions are stored on the server.
You can also check if sessions are working properly with a testing route.

I had this issue, for me the problem was
SESSION_DOMAIN=custom_domain_here
Setting in my .env file, which was different between production and local. This will cause the sessions to be created incorrectly for the domain and throw a TokenMismatch.
Hope this helps someone.

I had the same problem you have to create token in your configuration file.
Try either built in artisan command $ php artisan key:generate or create the key manually.

Probably you are doing something wrong with user login. Recently I was facing the same problem. In my case the problem that I was using Auth::login($user,true) instead of Auth::login($user) or Auth::attempt...
Secondly you also should check out if you have remember_token column in your user's database.
Thirdly you need to check where your session is stored.
I hope it will help!

I had the same issue, I used
<form role="form" method="POST" action="{{ url('laravel-master/login') }}">
<input type="hidden" name="_token" value="{{ session()->getToken() }}">
This line in my form view.

try to verify your Session file => App/Config
'domain' => 'ip adresse or Domaine name',
and if the domaine name has SSl certification
change the secure variable to True
i hope it will help you :D

Related

laravel MethodNotAllowedHttpException when do POST on online server

I have got MethodNotAllowedHttpException when running on online server, but on local server it runs well.
The PHP version is same, the method is used POST.
The other POST methods are runs well except this one.
on blade.php
<form action="{{ route('update.product') }}" method="POST" enctype="multipart/form-data" class="form-horizontal js-form">
on routes/web.php
Route::post('/updateProduct', [
'uses' => 'AdminController#updateProducts',
'as' => 'update.product'
]);
Update:
After I changed the route into 'get'
Route::get('/updateProduct', [
'uses' => 'AdminController#updateProducts',
'as' => 'update.product'
]);
it reach the updateProducts function.
but of course there is no data to process. So, why my post method form sent the get method? and on the browser developer tools I've got POST?
but on my local server it runs well only on online server I've got this issue.
browser dev tools
Can you try using different method if you use laravel collective.
{!! Form::open(['url' => 'client/store','method'=>'post','id'=>'client-register']) !!}
and in route it must be
Route::post('client/store', 'ClientController#store')>name('client.store').
or you can write your action
action="{{URL::to('client/store')}}"
At first see if routes are define properly.
And also you can try clearing the cache using artisan command.
php artisan config:cache
Hope it helps.
This issue occurs due to a missing module extension PDO database on the server, so upload file into the application will throws error.
Installing the module extension will resolve the issue.

Laravel 419 Error - VerifyCsrfToken issue

I have multiple Laravel sites hosted on the same server. With the latest site I've created, the contact form refuses to submit without throwing a 419 error. I have set up the routing in my web.php file just like the other websites, which have live, working contact forms, and I'm generating and sending the token exactly the same way - with {{ csrf_field() }}.
I found an answer to a similar question stating that you can disable Csrf checking by adding entries to the $except array in app/Http/Middleware/VerifyCsrfToken.php. I have verified that this does indeed resolve the 419 error:
protected $except = [
'contact',
'contact*',
];
But of course I wish to keep the Csrf functionality, and I only updated the $except array for troubleshooting value.
Does anyone know what may be different about the new Laravel environment that would have this 419 behavior despite passing the generated token? I have tried updating a number of ENV settings and toggling different things, but nothing other than modifying the $except array has had any influence on the issue.
Update
Since there has been a bit of discussion so far, I figured I'd provide some additional info and code.
First, this is an ajax form, but don't jump out of your seat just yet. I have been testing the form both with and without ajax. If I want to test with ajax, I just click the button that's hooked up to the jQuery listener. If not, I change or remove the button's ID, or run $("#formName").submit(); in the console window.
The above (ajax, old-fashioned submit, and the jquery selector with .submit();) all result in the exact same response - a 419 error.
And for the sake of completeness, here's my ajax code which is working on all of the other websites I'm hosting. I define a postData array to keep it all tidy, and I added a console.log() statement directly after it to (again) confirm that token is generated just fine and is being passed correctly with the request.
var postData = {
name: $("#name").val(),
email: $("#email").val(),
message: $("#message").val(),
_token: $("input[name=_token]").val()
};
console.log(postData);
$.post("/contact", postData, function (data) {
...
Any ideas? Could there be a configuration issue with my ENV or another file?
Progress Update!
Because the other sites are working just fine, I cloned an old site and simply overwrote the files that I changed for the new website, and bam! It's working now. Doing a little bit more digging, I ran php artisan --version on the cloned version of the site versus the non-working version, and here are the results:
Working Version: Laravel Framework 5.7.3
Non-working Version: Laravel Framework 5.7.9
Perhaps this is a bug with Laravel? Or perhaps some packages on my server are out of date and need to be updated to work with the new version of Laravel?
TLDR: This post contains lots of potential issues and fixes; it is intended for those scouring for related bonus information when stuck.
I just encountered this error using Laravel Sanctum in what looks like improperly setup middleware. Sanctum uses the auth:sanctum middleware for the guard, which is some kind of extension of the auth guard of which Laravel uses as the default, but session is handled by the web middleware group.
I can't exactly verbalize some of this internal-Laravel stuff; I am more experienced with JavaScript than PHP at the moment.
In my api.php file, I had the login/register/logout routes, and in my Kernel.php file, I copied \Illuminate\Session\Middleware\StartSession::class, from the web group into the api group.
I had to do that to fix my login unit test that was throwing an error about "Session store not on request". Copying that allowed me my postJson request to work in the unit test, but sometime later, I started seeing 419 CSRF error posting from the JavaScript app (which is bad because it worked fine earlier).
I started chasing some filesystem permission red-herring in the /storage/framework/sessions folder, but the issue wasn't that (for me).
I later figured out that with Laravel Sanctum and the default AuthenticatesUsers trait, you must use the web guard for auth, and the auth:sanctum middleware for protected routes. I was trying to use the api guard for auth routes and that was central to my 419 errors with the AuthenticatesUsers trait.
If anyone gets 419 while CSRF was working or should work, I recommend doing some \Log::debug() investigations at all the key points in your system where you need these to work:
Auth::check()
Auth::user()
Auth::logout()
If you get strange behaviour with those, based on my observations, there is something wrong with your config related to sessions or something wrong with your config related to web, api guards.
The guards have bearing on the AuthManager guard which maintains state over multiple requests and over multiple unit tests.
This is the best description I found, which took over a week for me to discover:
Method Illuminate\Auth\RequestGuard::logout does not exist Laravel Passport
As a random final example, if your session is somehow generating the CSRF token using data from the web middleware group while your routes are set to use api, they may interpret the received CSRF incorrectly.
Besides that, open Chrome dev tools and goto the Applications tab, and look at the cookies. Make sure you have the XSRF-TOKEN cookie as unsecure (ie: not httpOnly).
That will allow you to have an Axios request interceptor such as this:
import Cookies from 'js-cookie';
axios.interceptors.request.use(async (request) => {
try {
const csrf = Cookies.get('XSRF-TOKEN');
request.withCredentials = true;
if (csrf) {
request.headers.common['XSRF-TOKEN'] = csrf;
}
return request;
} catch (err) {
throw new Error(`axios# Problem with request during pre-flight phase: ${err}.`);
}
});
That is how my current Laravel/Vue SPA is working successfully.
In the past, I also used this technique here:
app.blade.php (root layout file, document head)
<meta name="csrf-token" content="{{ csrf_token() }}">
bootstrap.js (or anywhere)
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
const token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
In my opinion, most problems will stem from an incorrect value in one or more of these files:
./.env
./config/auth.php
./config/session.php
Pay close attention to stuff like SESSION_DOMAIN, SESSION_LIFETIME, and SESSION_DRIVER, and like I said, filesystem permissions.
Check your nginx access.log and/or error.log file; they might contain a hint.
just found your issue on the framework repo.
It is not a laravel issue, your installation is missing write permissions on the storage folder, thus laravel can't write session, logs, etc.
You get a 419 error because you can't write to the files, thus you can't create a sessionn, thus you can't verify the csrf token.
Quick fix: chmod -R 777 storage
Right fix: move your installation to a folder where nginx/apache/your user can actually write.
If you are using nginx/apache, move you app there and give the right permissions on the project (chown -R www-data: /path-to-project)
If you are using php artisan serve, change it's permissions to your user: chown -R $(whoami) /path-to-project
You get it, let writers write and you're good.
Probably your domain in browser address bar does not match domain key in config/session.php config file or SESSION_DOMAIN in your env file.
I had the same issue, but the problem in my case was https. The form was on http page, but the action was on https. As a result, the session is different, which is causing the csrf error.
run this command
php artisan key:generate
I used the same app name for staging and prod, being staging a subdomain of prod. After changing name of app in staging it worked
We had this issue, it turned out that our sessions table wasn't correct for the version of Laravel we were using. I'd recommend looking to see if it's being populated or remaining empty (like ours was).
If it's empty, even when you have people visiting the site, I'd say that's what the issue is.
(If you're not using a database to store your sessions, obviously I'd suggest checking wherever you are instead.)

Laravel login The page has expired due to inactivity [duplicate]

My register page is showing the form properly with CsrfToken ({{ csrf_field() }}) present in the form).
Form HTML
<form class="form-horizontal registration-form" novalidate method="POST" action="{{ route('register') }}">
{{ csrf_field() }}
....
</form>
I am using inbuilt authentication for the users. Have not changed anything except the routes and redirects.
When I submit the form (just after reloading also), it gives that The page has expired due to inactivity. Please refresh and try again. error.
My be I am missing a very small thing. But not sure what it is. Any help?
Update
Found the issue. The session driver was set to array. Changed it to file and the error is gone now.
But what is wrong if I use array?
If you're coming to this answer directly from a search, make sure you have already added the csrf token to your form with {{ csrf_field() }} like the OP.
If you have your session driver set to file:
May have something to do with the storage_path not being writable. This is where it stores session data regarding tokens if you're using file based sessions. The can be verified with is_writable(config('session.files'))
For the OP, the session driver was set to array. Array is for testing only. Since data is not persisted, it will not be able to compare the token on the next request.
The array driver is used during testing and prevents the data stored
in the session from being persisted.
https://laravel.com/docs/5.5/session#configuration
Check config/session.php
Lastly, an issue I just had, we had a project which has the session domain and secure settings in config/session.php but the development site was not using HTTPS (SSL/TLS). This caused this generic error since sessions.secure was set to true by default.
I ran into the same issue in Laravel 5.5. In my case, it happened after changing a route from GET to POST. The issue was because I forgot to pass a CSRF token when I switched to POST.
You can either post a CSRF token in your form by calling:
{{ csrf_field() }}
Or exclude your route in app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
'your/route'
];
Try all of them.
composer dump-autoload
php artisan optimize
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
This caused because of Illuminate\Session\TokenMismatchException
look at this code sample how to handle it properly:
https://gist.github.com/jrmadsen67/bd0f9ad0ef1ed6bb594e
My case was solved with SESSION_DOMAIN, in my local machine had to be set to xxx.localhost. It was causing conflicts with the production SESSION_DOMAIN, xxx.com that was set directly in the session.php config file.
Some information is stored in the cookie which is related to previous versions of laravel in development. So it's conflicting with csrf generated tokens which are generated by another's versions. Just Clear the cookie and give a try.
For those who still has problem and nothing helped. Pay attention on php.ini mbstring.func_overload parameter. It has to be set to 0. And mbstring.internal_encoding set to UTF-8. In my case that was a problem.
I change permission to storage and error was gone. It seemed lack of permission was the issue.
sudo chmod -R 775 storage/
In my case, the site was fine in server but not in local. Then I remember I was working on secure website.
So in file config.session.php, set the variable secure to false
'secure' => env('SESSION_SECURE_COOKIE', false),
add #csrf in the form
and also go to VerifyCsrfToken.php
app->Http->Middleware->VerifyCsrfToken.php
protected $except = [
'paste your route here'
];
I have figured out two solution to avoid these error
1)by adding protected $except = ['/yourroute'] possible disable csrf token inspection from defined root.
2)just comment \App\Http\Middleware\VerifyCsrfToken::class line in protected middleware group in kernel
Short answer
Add the route entry for register in app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
'/routeTo/register'
];
and clear the cache and the cache route with the commands:
php artisan cache:clear && php artisan route:clear
Details
Every time you access a Laravel site, a token is generated, even if the session has not been started. Then, in each request, this token (stored in the cookies) will be validated against its expiration time, set in the SESSION_LIFETIME field on config/session.php file.
If you keep the site open for more than the expiration time and try to make a request, this token will be evaluated and the expiration error will return. So, to skip this validation on forms that are outside the functions of authenticated users (such as register or login) you can add the except route in app/Http/Middleware/VerifyCsrfToken.php.
I had the app with multiple subdomains and session cookie was the problem between those. Clearing the cookies resolved my problem.
Also, try setting the SESSION_DOMAIN in .env file. Use the exact subdomain you are browsing.
Be sure to have the correct system time on your web server. In my case, the vagrant machine was in the future (Jan 26 14:08:26 UTC 2226) so of course the time in my browser's session cookie had expired some 200+ years ago.
set mbstring.func_overload = 2
it helped me
I had the same problem but the problem is not in the framework but in the browser. I don't know why but google chrome blocks cookies automatically, in my case. After allowed cookies the problem was resolved.
Many time its happening because you are testing project in back date
Solution:
use incognito new tab then test it again.
reason:
in my case another user logged in with my admin panel
I encountered the same issue on Linux-mint but then realized that the htdocs folder had no full permissions. So I changed the permissions of all the subdirectories in the htdocs folder by doing: sudo chown -c -R $USER:$USER /opt/lampp/htdocs/*
Sign in to connect to the server.
Search Error
An error has occurred: search false You don't have the peais.
Search request is longer.

MethodNotAllowedHttpException in RouteCollection.php line 200:

I have these route declaration here
//Skill
Route::get('skill','SkillController#index');
Route::get('skill/create','SkillController#create');
Route::post('skill/store','SkillController#store');
Route::get('skill/{id}','SkillController#show');
Route::get('skill/{id}/edit', 'SkillController#edit');
Route::post('skill/{id}/update','SkillController#update');
Route::delete('skill/{id}/destroy','SkillController#destroy');
With these routes, I can delete fine on local.
When I tried to delete on production, I kept getting
I know for sure, I had this line
Route::delete('skill/{id}/destroy','SkillController#destroy');
Local and Prod have the same codebase.
Local = Mac OS X
Prod = Ubuntu Server
What did I missed ?
The route is triggered from a form... Yes? Your form method should be POST, not DELETE and then you should add a hidden input to make it work as DELETE route, thus helping you maintain Route::delete().
Your form should look like this:
<form action="/foo/bar" method="POST">
<input type="hidden" name="_method" value="DELETE">
And your route:
Route::delete('skill/{id}/destroy','SkillController#destroy');
Read https://laravel.com/docs/5.7/routing#form-method-spoofing for more insight.
As your problem is on production only which is linux server I think it may be .htaccess issue.
Often web servers will be configured to block anything except GET and POST since 99% of the time they're all that are needed and there have been problems in the past with applications assuming the requests were one of those two.
You could try an .htaccess with
<Limit GET POST PUT DELETE>
Allow from all
</Limit>
(I'm not an expert at apache, this may not be exactly correct)
When you wrote down your request in browser address bar it supposed to be GET or POST. That's why you got the mistake.
MethodNotAllowedHttpException: It means that the route is correct, but method is mistaken. You used POST method - this method is automatic if you use browser. But you need DELETE method.
In order to use DELETE method you should use API client.
PhpStorm has API built-in API client. PHPStorm RESTApi client docs
But! For me the best way is to use Postman! Postman sending requests docs

Laravel CsrfToken expires on refresh after switching servers

I know my issue is not because of Laravel but most likely the php configuration (sessions), but I am not sure what to check. I was running this particular project on a homestead and it was fine. Now after I submit a form (it's a steps controller, post form -> go to step 2 etc.) and refresh the page my csrf token is invalid.
I thought it was because of session lifetime and such or generation of new token, but no .. the token is the same, but I still get TokenMismatchException after I refresh the page.
The environment is pretty much the same as the homestead (nginx (latest), php(5.6, I don't know what homestead had) ). The logins work fine, I stay logged in while browsing, but when I go through the steps this happens ..
Problem & Solution:
As per comments bellow where I forgot to update, I found out the problem was actually the fact, that the dev server was forced through cloudflare, but the base url in Laravel was left at http://... - I just added to AppServiceProvider
$this->app['request']->server->set('HTTPS', true);
and it wasn't doing the verification error.
Do you send a csrf token with the form you submit? If not: how did you build up your form, with FormBuilder or Html?
FormBuilder
In the formbuilder the CSRF token is already posted so it's not needed to send it.
Html
<form method="POST" action="/profile">
{{ csrf_field() }} //This is what you need!
...
</form>
You did not provide an error log, check in your laravel project for storage/logs and then provide us the error so we can help you.
As per comments bellow where I forgot to update, I found out the problem was actually the fact, that the dev server was forced through cloudflare, but the base url in Laravel was left at http://... - I just added to AppServiceProvider
$this->app['request']->server->set('HTTPS', true);
and it wasn't doing the verification error.

Categories