fruitcake / laravel-cors

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

Laravel 7 with ionic 5 have problem about Cors Policy #477

Open FabienRakoto opened 4 years ago

FabienRakoto commented 4 years ago

When i try to post or get something on the API it return always XMLHttpRequest at **************' from origin '******' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This is my middleware CORS :


    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', "*")
            ->header('Access-Control-Allow-Methods', "GET, POST, PUT, PATCH, DELETE, OPTIONS")
            ->header('Access-Control-Allow-Headers', "Origin, X-Requested-With, Accept, Content-Type, Authorization");
    }```

And this is my Kernel :

protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        // \Fruitcake\Cors\HandleCors::class,
        \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\Cors::class,
    ];

Can someone help me ?
barryvdh commented 4 years ago

So you created your own middleware?

FabienRakoto commented 4 years ago

i already use Fruitcake cors But the same issus so i create my own middleware

FabienRakoto commented 4 years ago

@barryvdh can you help me please ?

davidquon commented 4 years ago

@FabienRakoto Have a you had any luck with this?

I'm having a similar issue using this config/cors.php hitting an endpoint like https://site.com/api/endpoint. Seems like an issue with POST using a header with a Bearer token and post body. We're also using Laravel 7 with Ionic 5.

<?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,

];
davidquon commented 4 years ago

I was able to fix this with Ionic doing this. https://forum.ionicframework.com/t/ionic-4-laravel-cors/165763/6

        const headers = new HttpHeaders({
          'Authorization': "Bearer " + token,
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': '*',
          'Accept': 'application/json, text/plain'
        });
barryvdh commented 4 years ago

@davidquon I'm not sure how that is relevant, because this is a PHP package, not nodejs.

davidquon commented 4 years ago

@barryvdh This issue specified using Ionic 5 (client) to talk with a Laravel 7 API (server) which is using fruitcake/laravel-cors which is what is having issues when sending an authorization header like below which I've done with prior versions of Laravel when using spatie/laravel-cors.

      const headers = new HttpHeaders({
        'Authorization': "Bearer " + token,
        'Content-Type': 'application/json'
      });

If I send a POST with a header like https://github.com/fruitcake/laravel-cors/issues/477#issuecomment-664709886 then fruitcake/laravel-cors works as expected otherwise I receive a CORS error as specified in this issue. I thought this information might be helpful in determining the problem while also providing a workaround for others as well. While the JS code may not be correct for every language as a work around sending that type of header will hopefully help fix others having this CORS issue as well.

davidquon commented 4 years ago

Just to be a bit clearer https://github.com/fruitcake/laravel-cors/issues/477#issuecomment-664709886 is what I did using Ionic 5 (client-side) to make the Laravel 7 API (server-side) return the correct data and work around the CORS issue specified. I did not create my own middleware though for CORS and configured fruitcake/laravel-cors like this https://github.com/fruitcake/laravel-cors/issues/477#issuecomment-662146566 which should in theory accept all incoming requests unless I'm configuring something incorrectly. Thanks for the help @barryvdh.

davidquon commented 4 years ago

Setting supports_credentials to true helped solve it as well for me per this comment. https://github.com/fruitcake/laravel-cors/issues/478#issuecomment-664827785

Then I'm able to set the header to this in Ionic on the client-side:

      const headers = new HttpHeaders({
        'Authorization': "Bearer " + token,
        'Content-Type': 'application/json'
      });

and have the Laravel API respond correctly.

I saw supports_credentials but reading the comment above it thought it was for something else. 😥 Thanks for the help @barryvdh as I was hoping it was something like that. 👍

ghost commented 4 years ago

Hello i use ionic 4 for the front and laravel 7 for the backend and i have this error when i login with the front : Access to XMLHttpRequest at 'http://localhost:8000/api/connexion' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. but i dont understand before the app run correctely when i use composer update for another fonctionnality of my app mobile, the cors is wrong

celorodovalho commented 4 years ago

+1

bryce13950 commented 3 years ago

Is there any news on this? I have been using the older Laravel package for years without issues without issue, but for whatever reason I cannot get this package to work. The specific message I am getting is Access-Control-Allow-Origin cannot contain more than one origin., which seems weird. I really cannot tell if this issue is being generated from a bad response, or if there was a recent security change on mobile devices that is now causing this.

barryvdh commented 3 years ago

That most likely is because you are adding headers anywhere else (nginx/apache, php `header())

bryce13950 commented 3 years ago

As a note... It actually turned out to be caused by a temp block of code that was added to the project 5 years ago, which I did not find until today! @barryvdh thanks for the suggestion, and I appreciate the time you put into these projects.

DonxDaniyar commented 3 years ago

@FabienRakoto Have a you had any luck with this?

I'm having a similar issue using this config/cors.php hitting an endpoint like https://site.com/api/endpoint. Seems like an issue with POST using a header with a Bearer token and post body. We're also using Laravel 7 with Ionic 5.

<?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,

];

Hi guys! In my case the problem is paths. I use Passport so my route to authorize is /oauth/token. In paths i have pattern only for api/. So i add all path instead of api/*. Everything works!