laravel 如何检查控制器上的令牌(CSRF)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28557408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check a token (CSRF) on controller?
提问by LASH
There is some option on Laravel that we allow Laravel to create a token and test it on server side to pull up CSRF attacks.
Laravel 上有一些选项,我们允许 Laravel 创建一个令牌并在服务器端测试它以拉起 CSRF 攻击。
I found thison Laravel website, But didn't say how to check from Controller that is an attack or from a native and real page.
我在 Laravel 网站上找到了这个,但没有说明如何从 Controller 中检查是攻击还是从原生和真实页面。
How to check the token (CSRF) on controller?
如何检查控制器上的令牌(CSRF)?
采纳答案by Jerodev
Assuming you use laravel 4.x:
假设您使用 laravel 4.x:
You don't need to check this in your controller. defining the before
parameter tells laravel to check this automaticly.
你不需要在你的控制器中检查这个。定义before
参数告诉 laravel 自动检查。
Route::post('profile', array('before' => 'csrf', function(){
/* CSRF validated! */
}));
If you want to do something when the token is incorrect, you can change the filter in app/filters.php
. This one:
如果你想在令牌不正确的时候做点什么,你可以在app/filters.php
. 这个:
Route::filter('csrf', function()
{
if (Session::token() != Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
回答by lukasgeiter
Answer for Laravel 5
Laravel 5 的答案
In Laravel 5 middlewarereplaces filters. This is also true for CSRF. The middleware is enabled by default and is handled in App\Http\Middleware\VerifyCsrfToken
.
在 Laravel 5 中,中间件取代了过滤器。对于 CSRF 也是如此。中间件默认启用并在App\Http\Middleware\VerifyCsrfToken
.
It can be disabled by removing App\Http\Middleware\VerifyCsrfToken
in App\Http\Kernel
. And if moved to $routeMiddleware
...
可以通过删除App\Http\Middleware\VerifyCsrfToken
in来禁用它App\Http\Kernel
。如果搬到$routeMiddleware
...
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
'csrf' => 'App\Http\Middleware\VerifyCsrfToken',
];
... it can be used conditionally by adding it to a route:
...它可以通过将其添加到路由来有条件地使用:
Route::post('foo', ['middleware' => 'csrf', 'uses' => 'BarController@foo']);
Or in the controllers constructor:
或者在控制器构造函数中:
public function __construct(){
$this->middleware('csrf');
}