在自己的路由中使用(CORS)中间件?

时间:2019-02-21 09:28:26

标签: laravel cors

我正在构建一个具有自己路线的Laravel软件包。我正在尝试保护这些路由,以便只能使用来自同一域的请求来发出发布请求。

现在,在我的包composer.json中,我将CORS包(由Spatie设置)设置为依赖项,这安装得很好,我发布了配置,并更改了配置以仅允许来自不存在站点的请求。 (以进行测试)。

  

但是CORS规则似乎被忽略了。我认为是因为我正在从包裹中装载路线?有解决办法吗?

尝试

将Cors软件包添加到我的全局中间件中

protected $middleware = [
    \App\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\TrustProxies::class,
    \Spatie\Cors\Cors::class <-----------
];

将cors密钥添加到组中间件

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'cors' => \Spatie\Cors\Cors::class <--------
];

protected $middlewareGroups = [
    'api' => [
        'throttle:60,1',
        'bindings',
        'cors', <--------
    ],
];

Route::group([
    'prefix' => '/contact/api',
    'as' => 'contact.api.',
    'middleware' => 'api', <---------
], function () {
    Route::post('/', 'Me\\Contact\\Http\\Controllers\\InquiryController@store');
});

0 个答案:

没有答案