欢迎各位兄弟 发布技术文章
这里的技术是共享的
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'Illuminate\Foundation\Http\Middleware\VerifyCsrfToken',
];
public function handle($request, Closure $next)
{
// Add this:
if($request->method() == 'POST')
{
return $next($request);
}
if ($request->method() == 'GET' || $this->tokensMatch($request))
{
return $next($request);
}
throw new TokenMismatchException;
}
protected $middleware = [
// ....
'csrf' => 'Illuminate\Foundation\Http\Middleware\VerifyCsrfToken',
];
$router->post('url', ['middleware' => 'csrf', function() {
...
}]);
偏题的:
<meta name="csrf-token" content="{{{ Session::token() }}}">
<head>
App\Http\Middleware\VerifyCsrfToken
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'App\Http\Middleware\VerifyCsrfToken',
];
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
];
protected $middleware = [
];
App/Http/Kernal.php
VerifyCsrf
App\Http\Middleware\VerifyCsrf.php
<?php namespace App\Http\Middleware;
class VerifyCsrf extends \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken
{
/**
* Routes we want to exclude.
*
* @var array
*/
protected $routes = [
'api/some/route',
'another/route/here',
'yup/more/routes',
];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
* @throws \Illuminate\Session\TokenMismatchException
*/
public function handle($request, \Closure $next)
{
if ($this->isReading($request)
|| $this->excludedRoutes($request)
|| $this->tokensMatch($request))
{
return $this->addCookieToResponse($request, $next($request));
}
throw new \TokenMismatchException;
}
/**
* This will return a bool value based on route checking.
* @param Request $request
* @return boolean
*/
protected function excludedRoutes($request)
{
foreach($this->routes as $route)
if ($request->is($route))
return true;
return false;
}
}
App\Http\Kernel.php
<?php namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* @var array
*/
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
// 'App\Http\Middleware\VerifyCsrfToken',
'App\Http\Middleware\VerifyCsrf',
];
/**
* The application's route middleware.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
];
}
jnewing
说:
一个简单的选择是什么,我需要让一个RESTful API请求后创建自己的中间件,扩展了VerifyCsrfToken,然后加入你自己的排斥作用。在更换一个 App/Http/Kernal.php
用你自己的。我喜欢这个我想保持CSRF 打开(放)我认为这只是一个必须的安全。
在这个例子中,我打电话给我 VerifyCsrf
文件: App\Http\Middleware\VerifyCsrf.php
<?php namespace App\Http\Middleware; class VerifyCsrf extends \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken { /** * Routes we want to exclude. * * @var array */ protected $routes = [ 'api/some/route', 'another/route/here', 'yup/more/routes', ]; /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed * * @throws \Illuminate\Session\TokenMismatchException */ public function handle($request, \Closure $next) { if ($this->isReading($request) || $this->excludedRoutes($request) || $this->tokensMatch($request)) { return $this->addCookieToResponse($request, $next($request)); } throw new \TokenMismatchException; } /** * This will return a bool value based on route checking. * @param Request $request * @return boolean */ protected function excludedRoutes($request) { foreach($this->routes as $route) if ($request->is($route)) return true; return false; } }
然后我把它换了 App\Http\Kernel.php
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { /** * The application's global HTTP middleware stack. * * @var array */ protected $middleware = [ 'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode', 'Illuminate\Cookie\Middleware\EncryptCookies', 'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse', 'Illuminate\Session\Middleware\StartSession', 'Illuminate\View\Middleware\ShareErrorsFromSession', // 'App\Http\Middleware\VerifyCsrfToken', 'App\Http\Middleware\VerifyCsrf', ]; /** * The application's route middleware. * * @var array */ protected $routeMiddleware = [ 'auth' => 'App\Http\Middleware\Authenticate', 'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth', 'guest' => 'App\Http\Middleware\RedirectIfAuthenticated', ]; }
TokenMismatchException
tokensMatch
App\Http\Middleware\VerifyCsrfToken
/**
* Determine if the session and input CSRF tokens match.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function tokensMatch($request)
{
$token = $request->input('_token') ?: $request->session()->getToken();
if ( ! $token && $header = $request->header('X-XSRF-TOKEN'))
{
$token = $this->encrypter->decrypt($header);
}
return StringUtils::equals($request->session()->token(), $token);
}
use Symfony\Component\Security\Core\Util\StringUtils;
_token
input
public function handle($request, Closure $next)
{
if(in_array($request->path(), Config::get('auth.no_csrf'))) {
return parent::addCookieToResponse($request, $next($request));
}
return parent::handle($request, $next);
}
'no_csrf' => array('nocsrf/path/1', 'no/csrf/path/2'),
jasonhoule
说:
这是我做的是改变\程序\ \ \ verifycsrftoken HTTP中间件类检查路径,我不想有CSRF验证认证配置文件的方式。 public function handle($request, Closure $next) { if(in_array($request->path(), Config::get('auth.no_csrf'))) { return parent::addCookieToResponse($request, $next($request)); } return parent::handle($request, $next); }
在我加入auth.php \配置\ 'no_csrf' => array('nocsrf/path/1', 'no/csrf/path/2'),
我希望这有助于人
use Config;
jnewing
说:
一个简单的选择是什么,我需要让一个RESTful API请求后创建自己的中间件,扩展了VerifyCsrfToken,然后加入你自己的排斥作用。在更换一个 App/Http/Kernal.php
用你自己的。我喜欢这个我想保持CSRF 打开(放)我认为这只是一个必须的安全。
在这个例子中,我打电话给我 VerifyCsrf
文件: App\Http\Middleware\VerifyCsrf.php
<?php namespace App\Http\Middleware; class VerifyCsrf extends \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken { /** * Routes we want to exclude. * * @var array */ protected $routes = [ 'api/some/route', 'another/route/here', 'yup/more/routes', ]; /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed * * @throws \Illuminate\Session\TokenMismatchException */ public function handle($request, \Closure $next) { if ($this->isReading($request) || $this->excludedRoutes($request) || $this->tokensMatch($request)) { return $this->addCookieToResponse($request, $next($request)); } throw new \TokenMismatchException; } /** * This will return a bool value based on route checking. * @param Request $request * @return boolean */ protected function excludedRoutes($request) { foreach($this->routes as $route) if ($request->is($route)) return true; return false; } }
然后我把它换了 App\Http\Kernel.php
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { /** * The application's global HTTP middleware stack. * * @var array */ protected $middleware = [ 'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode', 'Illuminate\Cookie\Middleware\EncryptCookies', 'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse', 'Illuminate\Session\Middleware\StartSession', 'Illuminate\View\Middleware\ShareErrorsFromSession', // 'App\Http\Middleware\VerifyCsrfToken', 'App\Http\Middleware\VerifyCsrf', ]; /** * The application's route middleware. * * @var array */ protected $routeMiddleware = [ 'auth' => 'App\Http\Middleware\Authenticate', 'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth', 'guest' => 'App\Http\Middleware\RedirectIfAuthenticated', ]; }
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier {
protected $excludeRoutes = [
'api*'
];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
foreach( $this->excludeRoutes as $route )
{
if( $request->is( $route ) ) return $next($request);
}
return parent::handle($request, $next);
}
}
eduardostuart
说:
另一个解决方案: <?php namespace App\Http\Middleware; use Closure; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier; class VerifyCsrfToken extends BaseVerifier { protected $excludeRoutes = [ 'api*' ]; /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { foreach( $this->excludeRoutes as $route ) { if( $request->is( $route ) ) return $next($request); } return parent::handle($request, $next); } }
<?php namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
use Route;
use Closure;
class VerifyCsrfToken extends BaseVerifier {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$route = Route::getRoutes()->match($request);
$routeAction = $route->getAction();
if (isset($routeAction['nocsrf']) && $routeAction['nocsrf']) {
return $next($request);
}
return parent::handle($request, $next);
}
}
Route::any('test', [
'as' => 'external.test',
'uses' => 'TestController@test',
'nocsrf' => true,
]);
protected $except = [
'*',
];
holgerw1
说:
另一个可能的解决方案(虽然不理想): <?php namespace App\Http\Middleware; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier; use Route; use Closure; class VerifyCsrfToken extends BaseVerifier { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $route = Route::getRoutes()->match($request); $routeAction = $route->getAction(); if (isset($routeAction['nocsrf']) && $routeAction['nocsrf']) { return $next($request); } return parent::handle($request, $next); } }
在你的 routes.php然后你可以禁用特定的路线通过CSRF检查 Route::any('test', [ 'as' => 'external.test', 'uses' => 'TestController@test', 'nocsrf' => true, ]);
解决的办法是不理想的因为我们手工做的路由匹配,毕竟全球中间件完成了再做( sendrequestthroughrouter)。更the 比赛方法的确比我们真的需要更多的(结合,…)。
这种解决方案的优点是,您可以禁用CSRF的检查在你的 routes.php你不需要改变的东西如果你的路由的名称或URL不会改变。即它是比较容易的方式重构/维护你的路线。
李瓦西
说:其实你可以使用 路线::current()获得当前匹配的路由
holgerw1
说:
你遗憾的是不能使用路径::全球中间件current()自路由匹配的请求毕竟是全球中间件已经完成了。和CSRF验证者默认是所有路线全球中间件。
这将为特定的中间件虽然因为它们运行的路线路线匹配后的工作。
李瓦西
说:
哎呀!你是,当然,正确的是。
我是新到15所以我还没有时间去探究框架看万物如何执行-但没有任何具体的原因之前运行的路线是中间件相匹配?是让它正在改变本身的要求?即便如此,我不确定我是否想改变URL的用户试图访问的,所以这对我很有意义,虽然我可能忽略的东西-它看起来像它可能匹配的路线我们运行中间件之前。
谢谢!
return (new Pipeline($this->app))
->send($request)
->through($shouldSkipMiddleware ? [] : $this->middleware)
->then($this->dispatchToRouter());
config/custom.php
return [
/*
|--------------------------------------------------------------------------
| CSRF Exemptions
|--------------------------------------------------------------------------
|
| Routes we do not check for CSRF. Note: Should use other means of
| authenticating the origin, etc.
|
*/
'csrf_exempt_routes' => array(
'api/*',
),
];
foo/bar
/
app/Http/Middleware/VerifyCsrfToken.php
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
use Illuminate\Contracts\Encryption\Encrypter;
use Config;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [];
/**
* Create a new middleware instance. We set our exceptions in a
* config file.
*
* @param \Illuminate\Contracts\Encryption\Encrypter $encrypter
* @return void
*/
public function __construct(Encrypter $encrypter)
{
parent::__construct($encrypter);
$this->except = Config::get('custom.csrf_exempt_routes');
}
}
额外的学分
Route
public function __construct($methods, $uri, $action, $options)
...
$options = array('disable_csrf' => true);
Route::get('/foo/', function () { ... }, $options);
...
$except
<?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 = [
'api/*',
];
}
protected $except = [//"api/“/每一条路线开始/ API
laravel 4.2
filters.php
Route::filter('csrf', function () {
if(Config::get('auth.no_csrf')){
return;
}
if (Session::token() !== Input::get('_token')) {
throw new Illuminate\Session\TokenMismatchException('CSRF token not provided', 401);
}
});
routes.php
Route::group(['after' => 'no-cache', 'prefix' => 'api/v1'], function () {
// Disable CSRF protection
Config::set('auth.no_csrf', true);
Route::post('/test/search', ['auth.no_csrf' => 'val','uses' => 'Controllers\Api\SearchController@postSearch']);
});
来自 https://laravel.io/forum/11-14-2014-disabling-the-csrf-middleware-in-laravel-5