laravel-cors icon indicating copy to clipboard operation
laravel-cors copied to clipboard

Laravel 7 with ionic 5 have problem about Cors Policy

Open FabienRakoto opened this issue 5 years ago • 15 comments
trafficstars

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 ?

FabienRakoto avatar Jul 01 '20 14:07 FabienRakoto

So you created your own middleware?

barryvdh avatar Jul 01 '20 14:07 barryvdh

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

FabienRakoto avatar Jul 01 '20 14:07 FabienRakoto

@barryvdh can you help me please ?

FabienRakoto avatar Jul 03 '20 10:07 FabienRakoto

@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 avatar Jul 21 '20 22:07 davidquon

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'
        });

davidquon avatar Jul 28 '20 00:07 davidquon

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

barryvdh avatar Jul 28 '20 07:07 barryvdh

@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 avatar Jul 28 '20 15:07 davidquon

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 avatar Jul 28 '20 16:07 davidquon

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. 👍

davidquon avatar Jul 28 '20 17:07 davidquon

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

ghost avatar Oct 18 '20 13:10 ghost

+1

celorodovalho avatar Oct 18 '20 18:10 celorodovalho

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.

bryce13950 avatar Feb 04 '21 00:02 bryce13950

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

barryvdh avatar Feb 05 '21 13:02 barryvdh

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.

bryce13950 avatar Feb 05 '21 22:02 bryce13950

@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!

DonxDaniyar avatar Feb 20 '21 18:02 DonxDaniyar