fruitcake / laravel-cors

Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application
MIT License
6.27k stars 613 forks source link

Middleware API POST request with CORS issue (Passport and Auth0) #548

Open fabien-lopes opened 3 years ago

fabien-lopes commented 3 years ago

Hello,

I really need your help because I'm stuck since many days...

I started developing my application with Passport authentication and I recently added Auth0 authentication. Since this day, I don't know why but my POST/PATCH/PUT/DELETE requests with Data are blocked with the famous CORS error "No 'Access-Control-Allow-Origin' header is present on the requested resource.". All the GET requests works fine.

When I remove the Auth0 package it works again so I don't know if there is a conflict between Passport and Auth0 or if it's another thing.

Below the OPTIONS request :

image

Below the POST request :

image

You can find bellow my configuration. Many thanks for you help.

Here an extract of my Route file (tenant.php) :

Route::middleware(['api', InitializeTenancyByRequestData::class])->group(function () {

    // Azure Webhook
    Route::webhooks('/webhooks/azure', 'azure');

    // Classic Authentication & Password Routes
    Route::post('/register', [AuthController::class,'register']);
    Route::post('/login', [AuthController::class,'login']);
    Route::post('/password/forgot', [PasswordController::class,'forgot']);
    Route::post('/password/reset', [PasswordController::class,'reset'])->name('password.reset');

    // User authenticated Routes
    //Route::group(['middleware' => 'auth:api'], function() {
    Route::group(['middleware' => 'auth:auth0'], function() {
    //Route::group(['middleware' => ['auth:auth0,api']], function() {

        // Tenant
        Route::get('/tenants', [TenantController::class, 'show']);
        Route::patch('/tenants', [TenantController::class, 'update']);

Here my "cors.php" file :

'paths' => ['*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => ['*'],
    'allowed_headers' => ['*'],
    'exposed_headers' => ['*'],
    'max_age' => 0,
    'supports_credentials' => true,

Here an extract of my "AppServiceProvider.php" file :

/**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        // Passport for Tenancy
        Passport::ignoreMigrations();
        Passport::routes(null, ['middleware' => [InitializeTenancyByDomain::class, PreventAccessFromCentralDomains::class]]);

        // Debugbar
        if ($this->app->isLocal())
            $this->app->register(\Barryvdh\Debugbar\ServiceProvider::class);

        // Auth0
        $this->app->bind(Auth0UserRepository::class, CustomUserRepository::class);
    }

Here an extract of my "RouteServiceProvider.php" file :

protected function mapApiRoutes()
    {
        // App Api routes
        Route::middleware('api')
            ->namespace($this->namespace)
            ->group(base_path('routes/api.php'));

        // Tenant Api routes
        foreach ($this->centralDomains() as $domain) {
            Route::domain($domain)
                 ->middleware('api')
                 ->namespace($this->namespace);
        }
    }

    protected function centralDomains(): array
    {
        return config('tenancy.central_domains');
    }

Here an extract of my "Kernel.php" file :

protected $middleware = [
        TrustProxies::class,
        HandleCors::class,
        CheckForMaintenanceMode::class,
        ValidatePostSize::class,
        TrimStrings::class,
        ConvertEmptyStringsToNull::class,
    ];

Here an extract of my "App.php" file :

// Package Service Providers...

        // Application Service Providers...
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,
        MadeITBelgium\EmailDomainValidation\EmailDomainServiceProvider::class,
        Laravel\Passport\PassportServiceProvider::class,
        App\Providers\TenancyServiceProvider::class,
        OwenIt\Auditing\AuditingServiceProvider::class,
        App\Providers\HorizonServiceProvider::class,
        Superbalist\LaravelGoogleCloudStorage\GoogleCloudStorageServiceProvider::class,
        Auth0\Login\LoginServiceProvider::class,

Here an extract of my "TenancyServiceProvider.php" file :

protected function mapRoutes()
    {
        if (file_exists(base_path('routes/tenant.php'))) {
            Route::namespace('App\Http\Controllers')
                ->group(base_path('routes/tenant.php'));
        }
    }

    protected function makeTenancyMiddlewareHighestPriority()
    {
        $tenancyMiddleware = [
            // Even higher priority than the initialization middleware
            Middleware\PreventAccessFromCentralDomains::class,
            Middleware\InitializeTenancyByDomain::class,
            Middleware\InitializeTenancyBySubdomain::class,
            Middleware\InitializeTenancyByDomainOrSubdomain::class,
            Middleware\InitializeTenancyByPath::class,
            Middleware\InitializeTenancyByRequestData::class,
        ];

        foreach (array_reverse($tenancyMiddleware) as $middleware) {
            $this->app[Kernel::class]->prependToMiddlewarePriority($middleware);
        }
    }

Here an extract of my "auth.php" file :

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
            'hash' => false,
        ],
        'auth0' => [
            'driver' => 'auth0',
            'provider' => 'auth0',
        ]
    ],
hakouabh commented 2 years ago

I've been facing the same, problem.