Coder Social home page Coder Social logo

laravel-cors's Introduction

CORS Middleware for Laravel

Build Status Latest Stable Version Software License Total Downloads Fruitcake

Implements https://github.com/fruitcake/php-cors for Laravel

Note for users upgrading to Laravel 9, 10 or higher

This package is deprecated because all supported Laravel versions now include the CORS middleware in the core.

Since Laravel 9.2, this Middleware is included in laravel/framework. You can use the provided middleware, which should be compatible with the Middleware and config provided in this package. See https://github.com/laravel/laravel/pull/5825/files for the changes.

Steps to upgrade:

  1. Remove "fruitcake/laravel-cors" from your composer.json
  2. Replace \Fruitcake\Cors\HandleCors::class, with \Illuminate\Http\Middleware\HandleCors::class, in app/Http/Kernel.php

See https://github.com/fruitcake/php-cors for advanced usage. The config stays the same.

About

The laravel-cors package allows you to send Cross-Origin Resource Sharing headers with Laravel middleware configuration.

If you want to have a global overview of CORS workflow, you can browse this image.

Upgrading from 0.x (barryvdh/laravel-cors)

When upgrading from 0.x versions, there are some breaking changes:

  • A new 'paths' property is used to enable/disable CORS on certain routes. This is empty by default, so fill it correctly!
  • Group middleware is no longer supported, use the global middleware
  • The vendor name has changed (see installation/usage)
  • The casing on the props in cors.php has changed from camelCase to snake_case, so if you already have a cors.php file you will need to update the props in there to match the new casing.

Features

  • Handles CORS pre-flight OPTIONS requests
  • Adds CORS headers to your responses
  • Match routes to only add CORS to certain Requests

Installation

Require the fruitcake/laravel-cors package in your composer.json and update your dependencies:

composer require fruitcake/laravel-cors

If you get a conflict, this could be because an older version of barryvdh/laravel-cors or fruitcake/laravel-cors is installed. Remove the conflicting package first, then try install again:

composer remove barryvdh/laravel-cors fruitcake/laravel-cors
composer require fruitcake/laravel-cors

Global usage

To allow CORS for all your routes, add the HandleCors middleware at the top of the $middleware property of app/Http/Kernel.php class:

protected $middleware = [
  \Fruitcake\Cors\HandleCors::class,
    // ...
];

Now update the config to define the paths you want to run the CORS service on, (see Configuration below):

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

Configuration

The defaults are set in config/cors.php. Publish the config to copy the file to your own config:

php artisan vendor:publish --tag="cors"

Note: When using custom headers, like X-Auth-Token or X-Requested-With, you must set the allowed_headers to include those headers. You can also set it to ['*'] to allow all custom headers.

Note: If you are explicitly whitelisting headers, you must include Origin or requests will fail to be recognized as CORS.

Options

Option Description Default value
paths You can enable CORS for 1 or multiple paths, eg. ['api/*'] []
allowed_methods Matches the request method. ['*']
allowed_origins Matches the request origin. Wildcards can be used, eg. *.mydomain.com or mydomain.com:* ['*']
allowed_origins_patterns Matches the request origin with preg_match. []
allowed_headers Sets the Access-Control-Allow-Headers response header. ['*']
exposed_headers Sets the Access-Control-Expose-Headers response header. []
max_age Sets the Access-Control-Max-Age response header. 0
supports_credentials Sets the Access-Control-Allow-Credentials header. false

allowed_origins, allowed_headers and allowed_methods can be set to ['*'] to accept any value.

Note: For allowed_origins you must include the scheme when not using a wildcard, eg. ['http://example.com', 'https://example.com']. You must also take into account that the scheme will be present when using allowed_origins_patterns.

Note: Try to be as specific as possible. You can start developing with loose constraints, but it's better to be as strict as possible!

Note: Because of http method overriding in Laravel, allowing POST methods will also enable the API users to perform PUT and DELETE requests as well.

Note: Sometimes it's necessary to specify the port (when you're coding your app in a local environment for example). You can specify the port or using a wildcard here too, eg. localhost:3000, localhost:* or even using a FQDN app.mydomain.com:8080

Lumen

On Lumen, just register the ServiceProvider manually in your bootstrap/app.php file:

$app->register(Fruitcake\Cors\CorsServiceProvider::class);

Also copy the cors.php config file to config/cors.php and put it into action:

$app->configure('cors');

Global usage for Lumen

To allow CORS for all your routes, add the HandleCors middleware to the global middleware and set the paths property in the config.

$app->middleware([
    // ...
    Fruitcake\Cors\HandleCors::class,
]);

Common problems

Wrong config

Make sure the path option in the config is correct and actually matches the route you are using. Remember to clear the config cache as well.

Error handling, Middleware order

Sometimes errors/middleware that return own responses can prevent the CORS Middleware from being run. Try changing the order of the Middleware and make sure it's the first entry in the global middleware, not a route group. Also check your logs for actual errors, because without CORS, the errors will be swallowed by the browser, only showing CORS errors. Also try running it without CORS to make sure it actually works.

Authorization headers / Credentials

If your Request includes an Authorization header or uses Credentials mode, set the supports_credentials value in the config to true. This will set the Access-Control-Allow-Credentials Header to true.

Echo/die

If you use echo(), dd(), die(), exit(), dump() etc in your code, you will break the Middleware flow. When output is sent before headers, CORS cannot be added. When the script exits before the CORS middleware finishes, CORS headers will not be added. Always return a proper response or throw an Exception.

Disabling CSRF protection for your API

If possible, use a route group with CSRF protection disabled. Otherwise you can disable CSRF for certain requests in App\Http\Middleware\VerifyCsrfToken:

protected $except = [
    'api/*',
    'sub.domain.zone' => [
      'prefix/*'
    ],
];

Duplicate headers

The CORS Middleware should be the only place you add these headers. If you also add headers in .htaccess, nginx or your index.php file, you will get duplicate headers and unexpected results.

No Cross-Site requests

If you are not doing Cross-Site requests, meaning if you are not requesting site-a.com/api from site-b.com, your browser will not send the Origin: https://site-b.com request header, CORS will be "disabled" as the Access-Control-Allow-Origin header will be also missing. This happens because requests are being dispatched from the same and no protection is needed in this case.

License

Released under the MIT License, see LICENSE.

laravel-cors's People

Contributors

adamwathan avatar adrum avatar ajthinking avatar alexmayo avatar anteriovieira avatar antonioribeiro avatar arnidan avatar barryvdh avatar bencromwell avatar binhqx avatar casperhr avatar chimit avatar cozylife avatar danhunsaker avatar dczajkowski avatar driesvints avatar erikdonohoo avatar gabrieldeveloper avatar grahamcampbell avatar haakym avatar honeroku avatar hootlex avatar jasonmccreary avatar joaorobertopb avatar joshuajabbour avatar krisell avatar krsriq avatar lex111 avatar omranic avatar webpatser avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-cors's Issues

Installation error

I am trying to install the package in L5 project , but I got those errors now

 composer require barryvdh/laravel-cors 0.5.x@dev
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: don't install laravel/framework v5.0.27
    - Conclusion: don't install laravel/framework v5.0.26
    - Conclusion: don't install laravel/framework v5.0.25
    - Conclusion: don't install laravel/framework v5.0.24
    - Conclusion: don't install laravel/framework v5.0.23
    - Conclusion: don't install laravel/framework v5.0.22
    - Conclusion: don't install laravel/framework v5.0.21
    - Conclusion: don't install laravel/framework v5.0.20
    - Conclusion: don't install laravel/framework v5.0.19
    - Conclusion: don't install laravel/framework v5.0.18
    - Installation request for barryvdh/laravel-cors 0.5.x@dev -> satisfiable by barryvdh/laravel-cors[0.5.x-dev].
    - Conclusion: don't install laravel/framework v5.0.17
    - Conclusion: remove laravel/framework v5.0.16
    - barryvdh/laravel-cors 0.5.x-dev requires illuminate/support ~5.0.17 -> satisfiable by laravel/framework[v5.0.17, v5.0.18, v5.0.19, v5.0.20, v5.0.21, v5.0.22, v5.0.23, v5.0.24, v5.0.25, v5.0.26, v5.0.27], illuminate/support[v5.0.22, v5.0.25, v5.0.26].
    - don't install illuminate/support v5.0.22|don't install laravel/framework v5.0.16
    - don't install illuminate/support v5.0.25|don't install laravel/framework v5.0.16
    - don't install illuminate/support v5.0.26|don't install laravel/framework v5.0.16
    - Installation request for laravel/framework == 5.0.16.0 -> satisfiable by laravel/framework[v5.0.16].


Installation failed, reverting ./composer.json to its original content.

302 redirect after preflight?

Is it possible to do a 302 redirect after preflight has occurred? ie: inside a filter that fires before a route. It doesn't appear like it works, but the response seems like something that should be allowed?

Here is a simple filter I was playing w/ that "should" redirect to an invalid session if the access_token is invalid, but it doesn't appear to work.

public function filter($route, $request, $data = null)                       
    {                                                                            
        //  Get the authorization header or fail                                 
        if ($authorization = Request::header('Authorization', false)) {          
            list($type, $token) = explode(' ', $authorization);                  
            if (is_null($auth = OAuth2::token($token)->first())) {               
                return Redirect::to('session/invalid'); // This redirect seems to fail?
            }

            ...

        } else {                                                                 
            //  The authentication header is invalid, redirect to let the user know.
            return Redirect::to('session/invalid');                              
        }                                                                        
    }  

I tried fiddling w/ my config options, but nothing has really seemed to work.

return array(
  'defaults' =>  array(
      'allow_credentials' => false,
      'allow_origin'=> array(),
      'allow_headers'=> array(),
      'allow_methods'=> array(),
      'expose_headers'=> array(),
      'max_age' => 0
  ),

  'paths' => array(
      '^/api/' => array(
          'allow_origin'=> array('*'),
          'allow_headers'=> array('Content-Type', 'Authorization'),
          'allow_methods'=> array('POST', 'PUT', 'GET', 'DELETE', 'OPTIONS'),
          'max_age' => 3600
      ),
      '^/session/' => array(
          'allow_origin'=> array('*'),
          'allow_headers'=> array('Content-Type', 'Authorization'),
          'allow_methods'=> array('GET', 'OPTIONS'),
          'max_age' => 3600
      )
  ),

);

Response

XMLHttpRequest cannot load http://foo.com/api/tracks/27d7de10ba-e353-455b-a3cb-ced9b4965141. The request was redirected to 'http://foo.com/session/invalid', which is disallowed for cross-origin requests that require preflight.

The Preflight OPTIONS headers are not appended when executing the link

Would like to apologize because I am still new to Laravel and Cors but I am using the v0.7 pull with laravel 5.0, i manage to install everything but I am facing a problem whereby my preflight OPTIONS are not returned with the necessary headers. Look at the image below:

vyubb

The link is being called by AngularJS v1.3.15 with $resource

I manage to make a dirty override by adding those 3 lines in route.php but i do not want to maintain with such approach

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: ACCEPT, CONTENT-TYPE, X-CSRF-TOKEN");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, DELETE");

I wonder if someone could provide me with a guide on how to properly work this module. Thanks

I also have a topic in Stackoverflow which also records the updated I have done.

Does not work correctly with custom response

Just been trying this out with my API project and it doesn't seem work if you use requests such as:

App::error(function(Exception $e) {
  // ...

  return Response::json();
});

It only seems to work from within the standard request-response flow.

Conflict with dingo/api

I don't know if this is a bug on dingo/api or laravel-cors side, or if it's just that I messed up with the implementation, but I built up an api using https://github.com/dingo/api and wanted to use this package to handle the CORS. For some reason, I couldn't ever get the OPTIONS requests to return the correct information when going through the dingo/api. For example, my routes file looked somewhat like the following:

$api = app( 'Dingo\Api\Routing\Router' );
$api->version( 'v1',['middleware'=>'cors', function ( $api ) {
    $pong = function () {
        return "pong";
    };
    $api->get( '/ping', $pong );
    $api->put( '/ping', $pong );
    $api->post( '/ping', $pong );
    $api->delete( '/ping', $pong );
}
Route::match(['get','put','update','delete','post'], '/test', ['middleware'=>'cors', 'uses' => function () {
    return "Test";
}] );

When running cors requests through the standard laravel route, I didn't have any problems. However, when running through the dingo api router (/ping), the OPTIONS preflight wouldn't return the correct information. I then tried adding \Barryvdh\Cors\HandleCors::class to the $middleware array in the kernel, and still no luck. I finally got it working by adding both HandleCors and \Barryvdh\Cors\HandlePreflight::class to the $middleware array, even though it looks like the boot process should be dynamically adding that anyway.

So, to sum things up, the fix for me is to make the middleware look like the following:

    protected $middleware = [
        \\ ... All the normal middleware stuff ... \\
        \Barryvdh\Cors\HandleCors::class,
        \Barryvdh\Cors\HandlePreflight::class
    ];

Also, the required composer items are as follows:

    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
        "dingo/api": "~0.10",
        "tymon/jwt-auth": "~0.5",
        "doctrine/dbal": "~2.3",
        "watson/validating": "~1.0",
        "guzzlehttp/guzzle": "~5.0",
        "guzzlehttp/oauth-subscriber": "0.2.*",
        "barryvdh/laravel-cors": "0.7.x"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1",
        "barryvdh/laravel-ide-helper": "^2.0"
    },

OPTIONS request returns 405

When I add your package and configure it correctly the OPTIONS pre-flight requests returns a 405. Is this an issue with my webserver by any chance? This is my configuration:

    'paths' => [
        '*' => [
            'allowedOrigins' => ['*'],
            'allowedHeaders' => ['Content-Type'],
            'allowedMethods' => ['POST', 'PUT', 'GET', 'DELETE', 'PATCH', 'OPTIONS'],
            'maxAge' => 3600,
        ],
    ],

If I manually add the headers (and not use your package) everything seems to work though:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

Although it seems then no pre-flight seems to be performed.

need help for enable Laravel-cors

Hi,

I'm new in laravel. I want to use ajax to get data from local source (ip: 192.168.1.123). This is my config file:

array( 'supportsCredentials' => false, 'allowedOrigins' => array('*'), 'allowedHeaders' => array('*'), 'allowedMethods' => array('*'), 'exposedHeaders' => array(), 'maxAge' => 0, 'hosts' => array(), ), 'paths' => array( 'api/*' => array( 'allowedOrigins' => array('*'), 'allowedHeaders' => array('*'), 'allowedMethods' => array('*'), 'maxAge' => 3600, ), '*' => array( 'allowedOrigins' => array('*'), 'allowedHeaders' => array('Content-Type'), 'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE'), 'maxAge' => 3600, 'hosts' => array('api.*'), ), ), ``` ); When I use ajax, the error occur: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.1.123/. This can be fixed by moving the resource to the same domain or enabling CORS." Please advise if the config file is correct or not. Thanks

documentation confusion: allowedMethods can be set to array('*')

In the cors.php config file:

allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
to accept any value, the allowed methods however have to be explicitly listed.

The latter statement seems to contradict allowedMethods can be set to array('*')

So should I set the allowedMethods to

[
  // ......
  'allowedMethods'      => ['*'],
  // ......
]

or

[
  // ......
  'allowedMethods'      => ['DELETE', 'GET', 'OPTION', 'PATCH', 'POST', 'PUT'],
  // ......
]

?

Did exactly as described in the readme but is not working..

I tried different ways before stumbling upon this package. Did exactly as described in the readme file but the error still exists.

FIrst, wanted to debug it myself and so added the Allow headers on htaccess file, then added headers in the routes.php file. After doing this, I ran a curl command just to check if the headers are there and here is the output:

HTTP/1.1 302 Found
Server: cloudflare-nginx
Date: Sun, 19 Apr 2015 13:49:29 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: __cfduid=d1c27a79007c4dfc538ea9966de7702331429451369; expires=Mon, 18-Apr-16 13:49:29 GMT; path=/; domain=.[masked].com; HttpOnly
X-Powered-By: PHP/5.5.9-1ubuntu4.7
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, PUT, POST, DELETE
Access-Control-Allow-Headers: Origin, Accept, Set-Cookie, Location, CF-Ray, Connection, Transfer-Encoding, Cache-Control, X-XSRF-Token, Content-type, X-Powered-By
Cache-Control: no-cache
Set-Cookie: XSRF-TOKEN=eyJpdiI6ImVkSmRqNFBPQ2ZcLzBjMDJkeHJqeVVBPT0iLCJ2YWx1ZSI6IjJvc1VxN2FTR0xTbHB1NUJ1cnlERmp3eUFybEFHbjIzdlkzVk1nZldjTjliNFhxV2NXTk0za3BUUndBdmRrWStEVStoTnJCOW11MWRWTzcxZ25HdHh3PT0iLCJtYWMiOiIyYzBjNjM5ZjFjNjI1NjY3NDljYWFlZjNkOTExZTRmYjNlZGMyY2Q2Y2Q2MGU0MDQ2MzNiODk5MjdjZGRhMjkzIn0%3D; expires=Sun, 19-Apr-2015 15:49:29 GMT; Max-Age=7200; path=/
Set-Cookie: laravel_session=eyJpdiI6IjE5a29zdUNESk1PbjMrbE5cL1NYTmx3PT0iLCJ2YWx1ZSI6ImlBZHp6cFZxUjAyeUhNeWp2cWNmVlBQSk9PWkNhRU41XC9rYzJhXC8yTEdTQ0xCcXZRbUZFM0lJSWhWNTVRa1c4OGRTMWZ2N3haZmNHRldcL2VqR09xOE5RPT0iLCJtYWMiOiI5MDhhYzgzMzdhN2QxNWFi:

Clearly, the access headers are present but the no allow origin error still appears.

Then did a fresh install of laravel just to be sure. It's still there.

I know a lot of you have got it working. Hence asking for help.

Any help is much appreciated! Thanks :)

simply does not work

I followed the installation procedure. I am getting the same error.

Please advise.

TokenMismatchException in VerifyCsrfToken.php line 53

I feel as though I run into this EVERYTIME.

I've set up laravel-cors per the instructions. When issuing a POST command I'm getting the following error from the server:

TokenMismatchException in VerifyCsrfToken.php line 53

Stack:

in VerifyCsrfToken.php line 53
at VerifyCsrfToken->handle(object(Request), object(Closure))
at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 54
at ShareErrorsFromSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 62
at StartSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure))
at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 42
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 122
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 87
at Kernel->handle(object(Request)) in index.php line 53

My routes.php:

Route::group(['prefix'=> 'api/v1', 'after' => 'allowOrigin', 'middleware'=>'cors'], function() {
    Route::resource('programs', 'ProgramController');
    Route::resource('programEvents', 'ProgramEventController');
    Route::resource('recruitingEvents', 'RecruitingEventController');
    Route::resource('subscriptions', 'SubscriptionController');
});

My config/cors.php file:

return [
    /*
     |--------------------------------------------------------------------------
     | Laravel CORS
     |--------------------------------------------------------------------------
     |

     | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*') 
     | to accept any value, the allowed methods however have to be explicitly listed.
     |
     */
    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['GET', 'POST', 'PUT',  'DELETE'],
    'exposedHeaders' => [],
    'maxAge' => 0,
    'hosts' => [],
];

My request's headers:

POST /api/v1/subscriptions HTTP/1.1
Host: recruiter-sync-server-api
Connection: keep-alive
Content-Length: 72
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Content-Type: application/json; charset=UTF-8
Referer: http://localhost:4200/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8

What am I missing?

allow a list of domains to use the api

Hi,

I want to allow a list of trusted domains to use the api. My first thought was to use the 'hosts' config to list the domains in an array. This didn't work. I also tried putting it in the 'allowedOrigins' array , same result.

'paths' => array(
        'v1/*' => array(
            'allowedOrigins' => array('*'),
            'allowedHeaders' => array('authorization','x-requested-with','apiKey','Content-Type'),
            'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE'),
            'maxAge' => 3600,
            'hosts' => array('abc.com','mytrustedweb.org'),
        ),

    ),

Is this possible with the new config file?

[L5] What is correct syntax to load custom config?

Hi @barryvdh ,

I successfully installed package et load provider and middleware.

To load custom configuration, i added this in ConfigServiceProvider:

public function register()
{
       config([
            'laravel-cors.defaults' => [
                'supportsCredentials' => false,
                'allowedOrigins'      => [],
                'allowedHeaders'      => [],
                'allowedMethods'      => [],
                'exposedHeaders'      => [],
                'maxAge'              => 0,
                'hosts'               => [],
            ],
            'laravel-cors.paths'    => [
                '*' => [
                    'allowedOrigins' => ['*'],
                    'allowedHeaders' => ['Content-Type'],
                    'allowedMethods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
                    'maxAge'         => 3600,
                    'hosts'          => ['api.*'],
                ],
            ]
        ]);
}

Is this syntax is correct ?

Because when i return laravel-cors config, i show default configuration :

// Return Laravel-cors configuration
Config::get('laravel-cors');

Output:

{
    "defaults": {
        "supportsCredentials": false,
        "allowedOrigins": [],
        "allowedHeaders": [],
        "allowedMethods": [],
        "exposedHeaders": [],
        "maxAge": 0,
        "hosts": []
    },
    "paths": {
        "api/*": {
            "allowedOrigins": [
                "*"
            ],
            "allowedHeaders": [
                "*"
            ],
            "allowedMethods": [
                "*"
            ],
            "maxAge": 3600
        },
        "*": {
            "allowedOrigins": [
                "*"
            ],
            "allowedHeaders": [
                "Content-Type"
            ],
            "allowedMethods": [
                "POST",
                "PUT",
                "GET",
                "DELETE"
            ],
            "maxAge": 3600,
            "hosts": [
                "api.*"
            ]
        }
    }
}

Thanks

Access-Control-Allow-Methods should be set per resource

From what I understand, Access-Control-Allow-Methods should be set specific to a resource. I noticed that if I did an OPTIONS request (without the Origin header), Laravel correctly outputs all the allowed methods for a resource using the Allow header.

< HTTP/1.1 200 OK
< Date: Fri, 20 Jun 2014 17:21:28 GMT
* Server Apache/2.2.15 (CentOS) is not blacklisted
< Server: Apache/2.2.15 (CentOS)
< X-Powered-By: PHP/5.5.11
< Allow: GET,HEAD,POST
< Cache-Control: no-cache
< X-Frame-Options: SAMEORIGIN
< Transfer-Encoding: chunked
< Content-Type: text/html; charset=UTF-8

But when I use the laravel-cors package (supplying Origin in the header), it outputs whatever is set in the config for all resources (even if my resource doesn't support that verb).

< HTTP/1.0 200 OK
< Date: Fri, 20 Jun 2014 17:25:54 GMT
< Server: Apache/2.2.15 (CentOS)
< X-Powered-By: PHP/5.5.11
< Cache-Control: no-cache
< Access-Control-Allow-Origin: localhost
< Access-Control-Max-Age: 3600
< Access-Control-Allow-Methods: POST, PUT, GET
< Access-Control-Allow-Headers: content-type, authorization, x-requested-with
< X-Frame-Options: SAMEORIGIN
< Connection: close
< Content-Type: text/html; charset=UTF-8
<

Isn't the point of the Access-Control-Allow-Methods to output the specific allowed methods for the resource?

If Laravel already has this information, can't we get it from the response object and insert the info in the Access-Control-Allow-Methods header?

twitter Oauth2.0 error

I got an error when i use twitter Oauth

Error in exception handler: Class laravel-cors.send does not exist in /var/www/html/dev-api2/vendor/laravel/framework/src/Illuminate/Container/Container.php:501

here is my setting

    'defaults' => array(
        'allow_credentials' => false,
        'allow_origin'      => array('*'),
        'allow_headers'     => array('*'),
        'allow_methods'     => array('*'),
        'expose_headers'    => array('*'),
        'max_age'           => 0
    ),

    'paths'    => array(
        '^/' => array(
            'allow_origin'  => array('*'),
            'allow_headers' => array('*'),
            'allow_methods' => array(
                'POST',
                'PUT',
                'GET',
                'DELETE',
                'OPTIONS'
            ),
            'max_age'       => 3600
        )
    ),

No Headers set on response to a POST request

I'm trying to do auth with Laravel, Backbone and cross-domain. With your laravel-cors, I can get the correct headers sent along with the pre-flight OPTIONS request, but once the POST is sent with user details to login, none of the headers specified below are ever sent along, so the browsers fails with No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have set up as follows

return array(
    'defaults' => array(
        'allow_credentials' => true,
        'allow_origin' => array('*'),
        'allow_headers' => array('*'),
        'allow_methods' => array('POST', 'PUT', 'GET', 'DELETE', 'OPTIONS'),
        'expose_headers' => array('*'),
        'max_age' => 0,
    ),

    'paths' => array(
        '^/' => array(
            'allow_origin' => array('*'),
            'allow_headers' => array('*'),
            'allow_methods' => array('POST', 'PUT', 'GET', 'DELETE', 'OPTIONS'),
            'max_age' => 3600,
        ),
    ),
);

My SessionController responds as follows to the POST

public function postIndex()
  {
    $email = Input::get('email');
    $password = Input::get('password');

    if( Auth::attempt(array('email' => $email, 'password' => $password), true ) )
    {
      return Response::json(array('success' => true), 200);
    }
    return Response::json(array('success' => false), 403);
  }

Do you have any idea with there would be no headers sent?

i have installed cors but still getting same error

hi i hve installed cors but still getting same error:

http://www.scrumy.co.uk/

register
sign in
create project
create a todo list
then add a task inside it

you will see the error

XMLHttpRequest cannot load http://scrumy.co.uk/projects/addtask. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.scrumy.co.uk' is therefore not allowed access. The response had HTTP status code 403.

Global exception handling should not be part of this middleware

I've been banging my head against the wall trying to figure out why my exceptions are not getting caught by the proper middleware and are instead getting rendered. After a few hours, I narrowed it down to this library, and specifically the block starting here: https://github.com/barryvdh/laravel-cors/blob/master/src/HandleCors.php#L50

We are executing this middleware on a route group which means that it runs first before any other middleware. Specifically, we are running this on an Oauth2 authorization route (https://github.com/lucadegasperi/oauth2-server-laravel). This Oauth2 library has it's own middleware for catching it's own request errors and handling them gracefully. However, laravel-cors is catching all exceptions and handling them without giving a chance for any other middlewares to operate on the request.

I understand that this change resulted from this issue (#32) where the headers were not set properly when an exception happens. I think a better way to go about this is to create a custom error handler for laravel-cors which would take the place of App\Exceptions\Handler. Or, possibly add a method that could be added to the handle() method in an existing handler which dealt with adding the proper headers. I am of the opinion that it is not the responsibility of laravel-cors to catch errors and render them. All that should happen is laravel-cors takes care of any headers that need to be set for the request. Global exception handling should be out of scope.

Exception handler

Hello,
How can I use this middleware with Laravel 5 app/Exceptions/Handler.php? Because when exception happen, this middleware does not set the headers.
Thanks!

Add Support for Validator

Currently there's no CORS when the Validator throws an error. This is annoying if you want to check which fields are missing

Laravel 5.0 Support

With the new middleware implementation in Laravel 5.0 this package no longer works.

preflight request 405 method not allowed

I have setup laravel-cors bundle with the basic config as show below.
'defaults' => array(
'allow_credentials' => false,
'allow_origin'=> array('*'),
'allow_headers'=> array('authorization,x-requested-with'),
'allow_methods'=> array('POST', 'PUT', 'GET', 'DELETE','OPTIONS'),
'expose_headers'=> array(),
'max_age' => 10
),

'paths' => array(
'^/api/' => array(
'allow_origin'=> array(''),
'allow_headers'=> array('Content-Type'),
'allow_methods'=> array('POST', 'PUT', 'GET', 'DELETE'),
'max_age' => 3600
),
'^/v1/' => array(
'allow_origin'=> array('
'),
'allow_headers'=> array('authorization,x-requested-with'),
'allow_methods'=> array('POST', 'PUT', 'GET', 'DELETE','OPTIONS'),
'max_age' => 10
)
),

I get the correct headers back but with a HTTP 405 error. what am i missing?
image

Fresh response object for preflight requests.

Hi barryvdh,

Thanks for the package, I have however noticed a problem.

In the preflight middleware the response object is obtained via the $next closure.

The problem with this is that if we use status codes in our api such as "400 Bad request" our preflight will also fail.

This means that we cannot display a useful message to the user.

I was able to fix this in the middleware by simply returning the the cors service's handlePreflightRequest response object.

public function handle($request, Closure $next)
{
    if ($this->cors->isPreflightRequest($request))
    {
        $response = $this->cors->handlePreflightRequest($request);
    }
    else
    {
        $response = $next($request);
    }

    return $response;

    //$response = $next($request);
    //
    //if ($this->cors->isPreflightRequest($request)) {
    //  $preflight = $this->cors->handlePreflightRequest($request);
    //  $response->headers->add($preflight->headers->all());
    //}
    //
    //return $response;
}

What do you think?

Thanks

Gareth :)

Not allowing requests on nested resources?

I am struggling with this issue for days.

This is the config:

'defaults' => array(
        'supportsCredentials' => false,
        'allowedOrigins' => array('*'),
        'allowedHeaders' => array('*'),
        'allowedMethods' => array('*'),
        'exposedHeaders' => array(),
        'maxAge' => 3600,
        'hosts' => array('*'),
    ),
    'paths' => array()

As you can see I have allowed every single thing!

This way all GET and PUT requests work perfectly.

But when I POST to

http://localhost/eyelander/server/public/api/areas/2/coordinates

I get

XMLHttpRequest cannot load http://localhost/eyelander/server/public/api/areas/1/coordinates. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.

I have tried this configuration too, but still no luck...

'defaults' => array(
        'supportsCredentials' => false,
        'allowedOrigins' => array('*'),
        'allowedHeaders' => array('*'),
        'allowedMethods' => array('*'),
        'exposedHeaders' => array(),
        'maxAge' => 0,
        'hosts' => array('*'),
    ),

    'paths' => array(
        '*' => array(
            'allowedOrigins' => array('*'),
            'allowedHeaders' => array('*'),
            'allowedMethods' => array('*'),
            'maxAge' => 3600,
            'hosts' => array('*'),
        ),
    )

Maybe I'm doing something wrong, but I don't have a single clue about what is wrong with it.

It performs the OPTIONS request and stalls

Request headers

OPTIONS /eyelander/server/public/api/areas/1/coordinates HTTP/1.1
Host: localhost
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
Access-Control-Request-Method: POST
Origin: http://localhost:9000
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36
Access-Control-Request-Headers: accept, content-type
Accept: */*
DNT: 1
Referer: http://localhost:9000/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4

Response headers

HTTP/1.0 200 OK
Date: Tue, 02 Sep 2014 07:28:53 GMT
Server: Apache/2.4.9 (Win32) OpenSSL/1.0.1g PHP/5.5.11
X-Powered-By: PHP/5.5.11
Cache-Control: no-cache
Access-Control-Allow-Origin: http://localhost:9000
Access-Control-Max-Age: 3600
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: ACCEPT, CONTENT-TYPE
Set-Cookie: laravel_session=eyJpdiI6ImhMV0RIXC9kUndLT01aVWNwSzl0dTh3PT0iLCJ2YWx1ZSI6IjB6eFRndUcwRUxVR0N2RXpQMU4xT1RRcmtxc0RFUkZsdjNmMDZcL3hXQk1MRnVncGc1S0NKTitaM2g2ZWZ4S2dLRW9tMDlucTZFdFpYaVpKXC9icWIxMFE9PSIsIm1hYyI6IjQ2Y2MzYTg4NzY3M2VkNjdkYTRlOTIwOWViOWRhM2JjY2FiMTdkN2M0NDUzMWE3Njc0NDBhZWYwMjkyZTliMTAifQ%3D%3D; expires=Tue, 02-Sep-2014 09:28:53 GMT; Max-Age=7200; path=/; httponly
Connection: close
Content-Type: text/html

Authorization:Bearer

Hi,

I'm writing a EmberJS webapp. To communicate with the my API (Laravel 4 + laravel-auth-token + laravel-cors), I'm using the "ember-simple-auth" library (https://github.com/simplabs/ember-simple-auth).
The authentication is working well. But I'm struggling with the Authorization.

For each requests, "ember-simple-auth" send an "Authorization:Bearer XXXXXXXX(...)" as token. But laravel-cors is waiting for a "auth_token" right?

How can I do to make those 2 libraries working together?

Thank you

Using custom response format

Is it possible to catch the responses from the middleware (403, 500) and transform the response to a json response ?

I am actually using this module for an API and when the CORS are wrong, I simply get a plain text message instead of the expected json

Tag for version 0.7.x missing

There doesn't seem to be a tag for version 0.7.0. I tried using the install instructions but couldn't get the 0.7.0 version to install unless I used dev-master in my composer.json
error-when-using-command-in-readme

Unable to install laravel-cors

I tried installing cors using the readme given on https://github.com/barryvdh/laravel-cors/tree/0.2 but it did not work with laravel 4.2.

After which I tried it with both "barryvdh/laravel-cors": "0.7.x" and "barryvdh/laravel-cors": "0.7" but got the same result.

Everytime I get the following error:
cors

I went through the issues section where people have tried "composer self-update" to solve their problem but even that did not help in my case.

What did I miss ?

don't install illuminate/support v5.0.0|don't install laravel/framework v5.1.10

$ composer require barryvdh/laravel-cors 0.4.x@dev

./composer.json has been updated
> php artisan clear-compiled
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for barryvdh/laravel-cors 0.4.x@dev -> satisfiable by barryvdh/laravel-cors[v0.4.0].
    - Conclusion: remove laravel/framework v5.1.10
    - Conclusion: don't install laravel/framework v5.1.10
    - barryvdh/laravel-cors v0.4.0 requires illuminate/support 5.0.x -> satisfiable by illuminate/support[v5.0.0, v5.0.22, v5.0.25, v5.0.26, v5.0.28, v5.0.33, v5.0.4].
    - don't install illuminate/support v5.0.0|don't install laravel/framework v5.1.10
    - don't install illuminate/support v5.0.22|don't install laravel/framework v5.1.10
    - don't install illuminate/support v5.0.25|don't install laravel/framework v5.1.10
    - don't install illuminate/support v5.0.26|don't install laravel/framework v5.1.10
    - don't install illuminate/support v5.0.28|don't install laravel/framework v5.1.10
    - don't install illuminate/support v5.0.33|don't install laravel/framework v5.1.10
    - don't install illuminate/support v5.0.4|don't install laravel/framework v5.1.10
    - Installation request for laravel/framework == 5.1.10.0 -> satisfiable by laravel/framework[v5.1.10].


Installation failed, reverting ./composer.json to its original content.

Laravel 5 Package not working

Im trying to make a post call from an angularjs app to my laravel 5 service. Installed your package and did what its on the read me.

But i cant get the package to work. Only if i comment the VerifyCsrfToken on Kernel.php it works

in my routes.php

Route::group(['prefix'=>'api', 'middleware' => 'cors'], function(){
    Route::post('login/auth', [function(){
        return 'some text';
    }]);
}); 

my VerifyCsrfToken.php

class VerifyCsrfToken extends BaseVerifier {
    protected $except = [
        'api/*'
    ];
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return parent::handle($request, $next);
    }
} 

my cors.php

<?php

return [
    /*
     |--------------------------------------------------------------------------
     | Laravel CORS
     |--------------------------------------------------------------------------
     |

     | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*') 
     | to accept any value, the allowed methods however have to be explicitly listed.
     |
     */
    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['GET', 'POST', 'PUT',  'DELETE'],
    'exposedHeaders' => [],
    'maxAge' => 0,
    'hosts' => [],
];

php56, Laravel 5.1: OPTIONS goes through POST doesn't

I am using this package very successfully in Laravel 5.

Today I wanted to upgrade to Laravel 5.1 which deprecates the usage of filters.

Therefore, I upgraded to laravel-cors 0.6.x, added the Middleware and suddenly the respective headers aren't added anymore.

My options request gets the appropriate headers and includes the information set in my config.
I tried debugging it and the fun part is, that the Middleware is not even reached when I send a post request. Looking at the error log I can find this:

[:error] [pid 26862] [client 127.0.0.1:54487] PHP Deprecated:  Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. To avoid this warning set 'always_populate_raw_post_data' to '-1' in php.ini and use the php://input stream instead. in Unknown on line 0, referer: http://127.0.0.1:8000/admin/
[:error] [pid 26862] [client 127.0.0.1:54487] PHP Warning:  Cannot modify header information - headers already sent in Unknown on line 0, referer: http://127.0.0.1:8000/admin/

Any ideas?

some routes won't be enabled

Sorry disturbing again, I have a problem and can't figure out what the problem should be

I have the following config

return array(

/*
 |--------------------------------------------------------------------------
 | Laravel CORS Defaults
 |--------------------------------------------------------------------------
 |
 | The defaults are the default values applied to all the paths that match,
 | unless overridden in a specific URL configuration.
 | If you want them to apply to everything, you must define a path with ^/.
 |
 | allow_origin and allow_headers can be set to * to accept any value,
 | the allowed methods however have to be explicitly listed.
 |
 */
'defaults' => array(
'supportsCredentials' => false,
'allowedOrigins' => array('*'),
'allowedHeaders' => array('*'),
'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE'),
'maxAge' => 3600,
'exposedHeaders' => array(),
'hosts' => array(),

),

'paths' => array(
'^/api/products/' => array(
'allowedOrigins' => array('
'),
'allowedHeaders' => array('*'),
'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE'),
'maxAge' => 3600,
),
),

);

following router

// =============================================
// API ROUTES ==================================
// =============================================
Route::group(array('prefix' => 'api', 'before' => 'auth.token'), function() {

Route::get('products/{id}', 'ProductController@show', array('only' => array('index', 'store', 'destroy', 'update', 'show', 'edit')));
Route::resource('products', 'ProductController', array('only' => array('index', 'store', 'destroy', 'update', 'show', 'edit')));

});

than on api/products I can access the restapi but if I call api/products/prodID

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at /api/products/1CE8-05J

CORS with PhoneGap App - Session is new on every request

Hi,

thanks for this extension!

I have installed laravel-cors with settings:

    'defaults' => array(
        'supportsCredentials' => true,
        'allowedOrigins' => array(),
        'allowedHeaders' => array(),
        'allowedMethods' => array(),
        'exposedHeaders' => array(),
        'maxAge' => 0,
        'hosts' => array(),
    ),

    'paths' => array(
        'api/*' => array(
            'allowedOrigins' => array('*'),
            'allowedHeaders' => array('*'),
            'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE'),
            'maxAge' => 3600,
        ),
        '*' => array(
            'allowedOrigins' => array('*'),
            'allowedHeaders' => array('*'),
            'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE'),
            'maxAge' => 3600,
            'hosts' => array('api.*'),
        ),
    ),

Then I create a route filter:

Route::filter('authJson', function()
{
    $user = User::getUserByAuthHeader();

    if(!is_null($user))
    {
        Auth::login($user);
    }
    else
    {
        $sessionError = [
            "error" => [
                "code" => 401,
                "message" => "Token is wrong ",
            ]
        ];

        return Response::json($sessionError, 401);
    }
});

All route-pages return his response with:

return Response::json($rs);

My jQuery Code:

            $.ajaxSetup({
                xhrFields: {
                    withCredentials: true
                },
            });

If the user is successful logged in, I at the header:

        $.ajaxSetup({
            headers: {
                "X-Authentication-Token": accessToken
            },
        });

This works fine. The User is logged in and can view all member pages.

Login-Response header, where **** session id ***** is the session id:

HTTP/1.1 200 OK
Date    Fri, 06 Jun 2014 11:17:43 GMT
Server  Apache/2.2.26 (Unix) DAV/2 PHP/5.5.10 mod_ssl/2.2.26 OpenSSL/0.9.8y
X-Powered-By    PHP/5.5.10
Cache-Control   no-cache
Access-Control-Allow-Origin *
Vary    Origin
Access-Control-Allow-Credentials    true
Set-Cookie  sid=**** session id *****; expires=Fri, 06-Jun-2014 13:17:43 GMT; Max-Age=7200; path=/; httponly
Set-Cookie  remember_**** session id *****; expires=Wed, 05-Jun-2019 11:17:43 GMT; Max-Age=157680000; path=/; httponly
Transfer-Encoding   chunked
Content-Type    application/json

Next request to get one user. First is OPTION Request:

OPTIONS /api/users/1 HTTP/1.1
Host    mydomain
Cache-Control   no-cache
Access-Control-Request-Method   GET
Pragma  no-cache
Origin  http://0.0.0.0:8001
User-Agent  Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36
Access-Control-Request-Headers  accept, access-control-allow-credentials, x-requested-with, x-authentication-token
Accept  */*
Referer http://0.0.0.0:8001/
Accept-Encoding gzip,deflate,sdch
Accept-Language de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4

Options Response:

HTTP/1.0 200 OK
Date    Fri, 06 Jun 2014 11:07:41 GMT
Server  Apache/2.2.26 (Unix) DAV/2 PHP/5.5.10 mod_ssl/2.2.26 OpenSSL/0.9.8y
X-Powered-By    PHP/5.5.10
Cache-Control   no-cache
Access-Control-Allow-Credentials    true
Access-Control-Allow-Origin http://0.0.0.0:8001
Access-Control-Max-Age  3600
Access-Control-Allow-Methods    POST, PUT, GET, DELETE
Access-Control-Allow-Headers    ACCEPT, ACCESS-CONTROL-ALLOW-CREDENTIALS, X-REQUESTED-WITH, X-AUTHENTICATION-TOKEN
Set-Cookie  sid=**** different session id *****; expires=Fri, 06-Jun-2014 13:07:41 GMT; Max-Age=7200; path=/; httponly
Connection  close
Content-Type    text/html

user GET Request:

GET /api/users/1 HTTP/1.1
Host    mydomain
Cache-Control   no-cache
Pragma  no-cache
Origin  http://0.0.0.0:8001
X-Requested-With    XMLHttpRequest
Accept  application/json, text/javascript, */*; q=0.01
Access-Control-Allow-Credentials    true
X-Authentication-Token  *** the auth token ***
User-Agent  Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36
Referer http://0.0.0.0:8001/
Accept-Encoding gzip,deflate,sdch
Accept-Language de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4

user GET Response:

HTTP/1.1 200 OK
Date    Fri, 06 Jun 2014 11:07:42 GMT
Server  Apache/2.2.26 (Unix) DAV/2 PHP/5.5.10 mod_ssl/2.2.26 OpenSSL/0.9.8y
X-Powered-By    PHP/5.5.10
Cache-Control   no-cache
Access-Control-Allow-Origin http://0.0.0.0:8001
Vary    Origin
Access-Control-Allow-Credentials    true
Set-Cookie  sid=**** another different session id *****; expires=Fri, 06-Jun-2014 13:07:42 GMT; Max-Age=7200; path=/; httponly
Transfer-Encoding   chunked
Content-Type    application/json

Whats didnt work is the Laravel Session. On every request I get a new Session ID.

My session config:

'driver' => 'file',
'lifetime' => 120,
'expire_on_close' => false,
'cookie' => 'sid',
'domain' => null,

Used:
Laravel 4.2
jQuery 2.1.1

I didnt know how to get the laravel session properly to work. Do I anything wrong?

Best regards,
Sebastian

Can't install for Laravel 5.1

I realise 5.1 isn't actually released yet. But it's so close I am developing a new project with it. I'm just wondering if laravel-cors requirement for illuminate/support needs to be so specific ~5.0.17 as composer won't install it with laravel 5.1. tymon/jwt-auth for example requires ~5.0.x which composer seems happier with.

The 'Access-Control-Allow-Origin' header contains multiple values

I'm using AngularJS App on the client side to access Laravel API hosted on IIS 8.5.It works fine when client is hosted on same domain.But when hosted on different domain it gives following error.

XMLHttpRequest cannot load http://example.com/api. The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost, *', but only one is allowed. Origin 'http://localhost' is therefore not

Web.config:

<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Imported Rule 1" stopProcessing="true">
                    <match url="^(.*)/$" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Redirect" url="/{R:1}" redirectType="Permanent" />
                </rule>
                <rule name="Imported Rule 2" stopProcessing="true">
                    <match url="^" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php" />
                </rule>
            </rules>
        </rewrite>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
                <add name="Access-Control-Allow-Headers" value="Origin, Content-Type, Authorization, Accept, X-Request-With" />
                <add name="Access-Control-Allow-Methods" value="GET, POST, PUT,  DELETE, OPTIONS" />
                <add name="Access-Control-Allow-Credentials" value="true" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration> 

Actual Response header:

Request Method:POST
Status Code:200 OK
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Origin, Content-Type, Authorization, Accept, X-Request-With
Access-Control-Allow-Methods:GET, POST, PUT,  DELETE, OPTIONS
Access-Control-Allow-Origin:http://localhost
Access-Control-Allow-Origin:*

Why 'Access-Control-Allow-Origin' echoed twice.
What is the right way to host API on IIS? Do I have to include headers in web.config file.

Config file issues

I've updated to laravel 4.1 and since then I'm getting the Origin is not allowed. I haven't change anything in my config file and when checking code is seems that the config file is not loaded from laravel-cors package.

The Preflight OPTIONS are returning a cookie which is different

Hello,

Although I set the withCredentials for the angularJS side of the call, the preflight OPTIONS are not sending a cookie but I am receiving one back from Laravel. How can we disable OPTIONS to return a cookie laravel_session?
It messes up the CORS as it sets a new session which will obviously be different on every POST.

Thanks!

see stack overflow thread here: http://stackoverflow.com/questions/28213329/angularjs-laravel-cors-post-stops-after-preflights-options?noredirect=1#comment44793071_28213329

POST or PUT gets same error

Hi,

I tried to use laravel-cors (2.0) with laravel 4.2 to update data, but I always get the same error:

XMLHttpRequest cannot load http://goc-rb:8010/api/clientes/historico/insert/1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://goc-rf:8010' is therefore not allowed access. The response had HTTP status code 500.

GET request works fine! PUT or POST return error.

My file configuration is:

    'defaults' => array(
        'supportsCredentials' => true,
        'allowedOrigins' => array(),
        'allowedHeaders' => array(),
        'allowedMethods' => array(),
        'exposedHeaders' => array(),
        'maxAge' => 900,
        'hosts' => array(),
    ),

    'paths' => array(
        'api/*' => array(
            'allowedOrigins' => array('*'),
            'allowedHeaders' => array('*'),
            'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE'),
            'maxAge' => 900,
        ),
        '*' => array(
            'allowedOrigins' => array('*'),
            'allowedHeaders' => array('Content-Type', 'X-Auth-Token'),
            'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE'),
            'maxAge' => 900,
            'hosts' => array('*'),
        ),
    ),

can you help me?
Thanks advanced!

Class 'Barryvdh\Cors\CorsServiceProvider' not found when running 'composer install/update' on 0.2.x

I am deploying a laravel 4.x application to a production machine. I am using the 0.2.x branch.

When running

composer install

or

composer update

I get the following error:

[root@webapps prod]# composer update
> php artisan clear-compiled
PHP Fatal error:  Class 'Barryvdh\Cors\CorsServiceProvider' not found in /var/www/html/apps/request-tracker/prod/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php on line 157

{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Class 'Barryvdh\\Cors\\CorsServiceProvider' not found","file":"\/var\/www\/html\/apps\/request-tracker\/prod\/vendor\/laravel\/framework\/src\/Illuminate\/Foundation\/ProviderRepository.php","line":157}}

Script php artisan clear-compiled handling the pre-update-cmd event returned with an error

  [RuntimeException]
  Error Output: PHP Fatal error:  Class 'Barryvdh\Cors\CorsServiceProvider' not found in /var/www/html/apps/request-tracker/prod/vendor/laravel/framework/src/Illuminate/Foundat
  ion/ProviderRepository.php on line 157

How do I solve for this?

Here is my composer file:

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "require": {
        "laravel/framework": "4.2.*",
        "loic-sharma/profiler":"1.1.*",
        "rhumsaa/array_column": "~1.1",
        "sidney/latchet": "dev-master",
        "brainboxlabs/brain-socket": "v1.0.0",
        "barryvdh/laravel-cors": "0.2.x",
        "maatwebsite/excel": "~1.3.0"
    },
    "repositories":[
        {
            "type": "vcs",
            "url": "https://github.com/sidneywidmer/latchet"
        }
    ],
    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan optimize"
        ],
        "pre-update-cmd": [
            "php artisan clear-compiled"
        ],
        "post-update-cmd": [
            "php artisan optimize"
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    },
    "minimum-stability": "dev"
}

And here is my app/config/app.php file:

<?php

return array(
    'debug' => true,

    'url' => 'http://localhost',

    'timezone' => 'UTC',

    'locale' => 'en',

    'key' => 'YourSecretKey!!!',


    'cipher'    =>  MCRYPT_RIJNDAEL_256,

    'providers' => array(

        **** truncated ****

        'Barryvdh\Cors\CorsServiceProvider',
        'BrainSocket\BrainSocketServiceProvider',
        'Maatwebsite\Excel\ExcelServiceProvider',

    ),

    'manifest' => storage_path().'/meta',


    'aliases' => array(
        **** truncated ****
    ),

    'profiler' => true,

);

Intermittent results behavior

I installed 0.4 branch with Laravel 5 and defined these rules (just to be sure that every request must be allowed):

return array(

    'defaults' => array(
        'supportsCredentials' => true,
        'allowedOrigins' => array('*'),
        'allowedHeaders' => array('*'),
        'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE'),
        'maxAge' => 3600,
    ),

    'paths' => array(
        'api/*' => array(
            'supportsCredentials' => true,
            'allowedOrigins' => array('*'),
            'allowedHeaders' => array('*'),
            'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE'),
            'maxAge' => 3600,
        ),
        '*' => array(
            'supportsCredentials' => true,
            'allowedOrigins' => array('*'),
            'allowedHeaders' => array('*'),
            'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE'),
            'maxAge' => 3600,
        ),
    ),

);

But when I make ajax requests, ramdomly some requests succeed and ramdomly some not, returning Cross-Origin Request Blocked.

Softwares and versions:
Laravel 5.0.16
Laravel Cors with last commit from 25 days ago
Composer version 1.0-dev (ab3622dff1db71024f327387408250208c139a0d) 2015-03-23 11:56:30
PHP 5.5.9
Apache 2.4.7

hhvm and laravel-cors - no cors headers beeing sent

Well, this is pretty weird to me. I replaced php5-fpm (5.6.9) with hhvm (3.8.1) today, suddenly CORS headers went missing on my API domain. I switched back to php5-fpm and CORS headers we're working again.

I have no explaination for this behaviour.

Anyone else experiencing the same issue?

OPTIONS method returning data in response

Although the pre-flight request works fine, I don't understand why it is responding with actual data in the response (see screenshot). As I understand a simple 200 OK response should be sufficient. Is there a setting in laravel-cors to configure this?
image
image

5.1, middleware doesn't appear to be working?

Hello,

I've used this package previously in 4.2 and it worked perfectly.

I'm now trying to use it with 5.1, but the middleware doesn't appear to be doing anything? Is it something still being worked on?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.