可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Hi Why my csrf token value is null ? And when i don't use token i havent TokenMismatchException!!!! how can i fix it ?
I dug deeper and found that a session is not being registered in SessionServiceProvider. Is there something that needs to be enabled for this to work by default? Since I am a Laravel beginner, I am not sure how to follow the advice above. How do I make sure that my routes are added under the "web" group?
<form method="post" action="<?php echo url('/form'); ?>">
<input type="hidden" name="_Token" value="{{ csrf_token() }}">
<input type="text" name="Title" placeholder="Title"><br>
<textarea rows="10" name="Content" placeholder="Content"></textarea><br>
<input type="submit" value="Send">
</form>
回答1:
Make sure your route has the web milddleware applied to it.
Pretty much any route where you will want sessions, csrf protection, encrypted cookies, session errors, etc ... you will need the 'web' middleware group applied.
Check your routes.php file for the route group like so:
Route::group(['middleware' => 'web'], function () {
//
});
Update: Since 5.2.27 The RouteServiceProvider
now puts all your routes in routes.php
in a route group that has the web
middleware applied for you.
回答2:
In Version 5.2 : You move Route into:
Route::group(['middleware' => ['web']], function () {
//Your route here
});
Have two way to use Token in form (https://laravel.com/docs/master/routing#csrf-protection):
// Vanilla PHP
<?php echo csrf_field(); ?>
// Blade Template Syntax
{{ csrf_field() }}
Or
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
回答3:
use
{!! csrf_token() !!}
instead of
{{ csrf_token() }}
回答4:
Make sure that session path is writable. If not, laravel compares null (no session token) with $_POST['_token'] value and throws mismatch error despite the real reason.
回答5:
Just incase anyone is still hitting this issue,
inside config/session.php my sessions essentially weren't working (even though they seemed alright for a while)
Make sure that the 'domain' variable is set to null!
Fixed everything for me as none of the other things where actually my issue.
Hope it helps someone.
回答6:
Edit your VerifyCsrfToken.php from Middleware folder to this
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$response->headers->set('Access-Control-Allow-Origin' , '*');
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
return $response;
}
}
I have the same issue as you, I'm on Laravel 5.2, I have also a token field on my form but still throwing me the error of "TokenMismatch" very annoying right?
回答7:
I think this is quite a deep problem as there can be many causes of this.
For me, i was upgrading from Laravel 5.1 to 5.2. I am also using the database to store my sessions.
It was giving me this error but when i checked the laravel error logs (/storage/logs) i found that Laravel 5.2 expects the session table to have user_id, ip_address and user_agent fields. Mine didn't. When i added these fields it all worked the same as before the upgrade.
So, my advice is to check the error log!
回答8:
This answer is for all the people who have already used {{ csrf_field() }}
after the <form>
tag in their view.blade.php
file and have also run the php artisan key:generate
command but are still getting the Token Mismatch error. These are the steps I took to resolve the TokenMismatchException error for one of my projects that was still in development.
Delete cache files from the following two folders within your laravel project:
- storage/framework/sessions/
- storage/framework/views/
After removing the cache files, clear your browser cache.
回答9:
Maybe you can use this : (src = https://laravel.com/docs/5.2/routing)
<form action="/foo/bar" method="POST">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
回答10:
I can confirm this problem, both csrf_token() and csrf_field() produce empty token fields in Laravel 5.2. According to the docs, both methods should still work but they don't appear to do so. My installation is completely fresh so either the docs are incorrect or a bug is present.
回答11:
You could just use this:
<form method="POST" action="/addUser" >
{!! csrf_field() !!}
...
</form>
回答12:
I have a same problem. I didn't find how to fix a core problem but I think that this is a decent fix:
Laravel 5.x: Redirect CSRF Errors to Previous Page
So instead to throw TokenMismatchException
redirect
user to previous page with with error message.
In order to do it override
VerifyCsrfToken.($request, Closure $next)
method.
Open App\Http\Middleware\VerifyCsrfToken.php
and got to base class(Illuminate\Foundation\Http\Middleware\VerifyCsrfToken
) and copy handle method inside App\Http\Middleware\VerifyCsrfToken.php
and change line that throws TokenMismatchException
to redirect to previous page. also add import use Closure;
. So after all changes, App\Http\Middleware\VerifyCsrfToken.php
will look like:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
/**
* Class VerifyCsrfToken
* @package App\Http\Middleware
*/
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
public function handle($request, Closure $next)
{
if (
$this->isReading($request) ||
$this->runningUnitTests() ||
$this->shouldPassThrough($request) ||
$this->tokensMatch($request)
) {
return $this->addCookieToResponse($request, $next($request));
}
//throw new TokenMismatchException;
return Redirect::back()->withError('Sorry, we could not verify your request. Please try again.');
}
}
Solution 2 is to use Caffeine For Laravel.
Caffeine For Laravel is a package designed to prevent users CSRF token from timing out on your site while filling out a form.
Mike, the package creator, wanted to have a secure way to make life easier for users who take their time filling out forms by keeping the token awake through a behind the scenes ajax call.
回答13:
I had same problem. Solved it by deleting all files into sessions folder.
The path of sessions folder is: yourApplication/storage/framework/sessions/
回答14:
To not verify the security on this form must go to the file path: config/auth.php on Laravel. In that file you should find (or create it) the line 'no_csrf' => array(),
This line is to add the routes that security can not be verified. In this arrangement you must add the path to your form, such as:
'No_csrf' => array('/form'),
回答15:
My suggestion is to use FormHelper
and Form::open()
in your view. Fomr and HTML helpers were removed from laravels core in version 5.0, but you can install them again following these instructions.
Anyway, there's a typo in your view. The correct field name is _token
and not _Token
. Maybe that's the problem