提问者:小点点

Laravel 7 Passport:被CORS政策阻止


当我向Laravel 7.3Passport API发出以下axios请求时:

let url = 'http://laravel.test/oauth/token'

let params = {
  client_id:  4,
  client_secret: 'FBkMiLI8ecdb4A8OhLRDGS1SasZP5NT7i9Qpp7bP',
  grant_type: 'password',
  username: 'me@home.com',
  password: '1qaz@WSX',
  scope: '*'
}

let headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type'
  }

axios.post(url, params, headers)
.then(response => {
      this.access_token = response['data']['access_token'];
      this.get_users_data()
  })
.catch(response => {
// eslint-disable-next-line
    console.log(response)
});

我在javascript控制台中遇到以下错误:

CORS策略已阻止从起源“http://localhost:3000”访问“http://laravel.test/oauth/token”处的XMLHttpRequest:对预飞行请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

此外,Laravel 7.3中的config/cors.php被配置为允许任何操作(默认情况下):

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => false,

];

我的要求有什么问题?


共2个答案

匿名用户

你的要求没什么问题。您的API资源具有CORS策略,该策略限制哪些域可以访问该资源。您得到的错误是告诉您资源没有允许从调用域访问的CORS头。

您需要将CORS策略设置为白名单您的域:http://localhost:3000。您可能会发现本文“在Laravel应用程序中处理COR”很有帮助:

最近我们发布了Laravel-CORS。这个包可以添加您的Laravel应用程序所必需的CORS头。

匿名用户

这个解决方案在AuthServiceProviders.php文件中对我很有效,但在美学上不正确:添加api前缀,以便config/cors完成它的工作,不要忘记添加它use luminlate\support\facades\route;

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Route;
use Laravel\Passport\Passport;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
        Route::prefix('api')->group(function () {
            Passport::routes();
        });
    }
}