为啥 Laravel 中间件适用于单个路由而不适用于一组路由

Posted

技术标签:

【中文标题】为啥 Laravel 中间件适用于单个路由而不适用于一组路由【英文标题】:Why Laravel middleware works for single routes but not group of routes为什么 Laravel 中间件适用于单个路由而不适用于一组路由 【发布时间】:2016-02-07 16:03:19 【问题描述】:

我添加了一个 CORS 中间件,它适用于单个路由:-

Route::get('example', ['middleware' => 'cors', function()
    return Response::json(array('name' => 'Steve Jobs', 'company' => 'Apple'));
]);

但是当我将它应用于路由组时,它会在控制台中出现错误:-

(index):1 XMLHttpRequest cannot load http://jotdot.mysite.com/api/authenticate. 
Response to preflight request doesn't pass access control 
check: No 'Access-Control-Allow-Origin' header is present on 
the requested  resource. Origin 'http://jotdotfrontend.mysite.com' is
therefore not allowed access.

我的路线组:-

Route::group(['middleware' => 'cors'], function () 
Route::group(['prefix' => 'api'], function()

    Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
    Route::post('authenticate', 'AuthenticateController@authenticate');
);
);

Cors.php

class CORS

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)

    header("Access-Control-Allow-Origin: *");

    // ALLOW OPTIONS METHOD
    $headers = [
        'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
        'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
    ];
    if($request->getMethod() == "OPTIONS") 
        // The client-side application can set only headers allowed in Access-Control-Allow-Headers
        return Response::make('OK', 200, $headers);
    

    $response = $next($request);
    foreach($headers as $key => $value)
        $response->header($key, $value);
    return $response;
    return $next($request);


我正在关注https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps 并尝试在不同的域上设置后端和前端。

谢谢

【问题讨论】:

【参考方案1】:

问题是基于路由的中间件从未应用于OPTIONS 请求自动生成的基于resource 的路由(因为Route::resource(...) 不会为options 方法生成路由?)。

所以,把你的 cors 中间件放在 app/Http/Kernel.php 的全局中间件组中,就在 VerifyCsrfToken 中间件之前:

/**
 * The application's global HTTP middleware stack.
 *
 * @var array
 */
protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Ankh\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\CORS::class, // here it is
    \App\Http\Middleware\VerifyCsrfToken::class,
];

并从routes.php 中完全删除它,例如:

// Route::group(['middleware' => 'cors'], function () 
Route::group(['prefix' => 'api'], function() 
    Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
    Route::post('authenticate', 'AuthenticateController@authenticate');
);
//);

【讨论】:

【参考方案2】:

你可以试试这个:

Route::group(['prefix' => 'api', 'middleware' => 'cors'], function()

    Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
    Route::post('authenticate', 'AuthenticateController@authenticate');
);

【讨论】:

@StacyJ 我认为问题在于当您尝试发送 POST 请求时,Laravel 将验证 CsrfToken。看看Laravel Csrf protection。您需要在line 20Kernel.php 文件中禁用此中间件以解决此问题。【参考方案3】:

这样试试,

Route::group([ 'prefix' => 'api', 'middleware' => 'App\Http\Middleware\CORS'], function() 
     Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
     Route::post('authenticate', 'AuthenticateController@authenticate');

);

【讨论】:

如何将中间件添加到组内的各个路由中?【参考方案4】:

您的原始标头不在您的标头数组中。不要使用 header() 设置原始标头,而是尝试将其与其他访问控制标头一起添加,如下所示:

// ALLOW OPTIONS METHOD
$headers = [
    'Access-Control-Allow-Origin'=> '*',
    'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
    'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];

【讨论】:

以上是关于为啥 Laravel 中间件适用于单个路由而不适用于一组路由的主要内容,如果未能解决你的问题,请参考以下文章

将自定义中间件添加到 Laravel Passport 端点

为啥 Dojo Tab Container 仅适用于浏览器调整大小

Laravel - 控制器中路由的中间件

2. 路由

多个控制器的单个 Laravel 路由

Laravel Orion 是不是适用于 Laravel 版本 6