Code Monkey home page Code Monkey logo

laravel-cors's Introduction

CORS Middleware for Laravel 5

Latest Version on Packagist Software License Build Status Total Downloads

Based on https://github.com/asm89/stack-cors

About

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

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

Features

  • Handles CORS pre-flight OPTIONS requests
  • Adds CORS headers to your responses

Installation

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

$ composer require barryvdh/laravel-cors

For laravel >=5.5 that's all. This package supports Laravel new Package Discovery.

If you are using Laravel < 5.5, you also need to add Cors\ServiceProvider to your config/app.php providers array:

Barryvdh\Cors\ServiceProvider::class,

Global usage

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

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

Group middleware

If you want to allow CORS on a specific middleware group or route, add the HandleCors middleware to your group:

protected $middlewareGroups = [
    'web' => [
       // ...
    ],

    'api' => [
        // ...
        \Barryvdh\Cors\HandleCors::class,
    ],
];

Configuration

The defaults are set in config/cors.php. Copy this file to your own config directory to modify the values. You can publish the config using this command:

$ php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

Note: When using custom headers, like X-Auth-Token or X-Requested-With, you must set the allowedHeaders to include those headers. You can also set it to array('*') 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.

return [
     /*
     |--------------------------------------------------------------------------
     | Laravel CORS
     |--------------------------------------------------------------------------
     |
     | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
     | to accept any value.
     |
     */
    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedHeaders' => ['Content-Type', 'X-Requested-With'],
    'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT',  'DELETE']
    'exposedHeaders' => [],
    'maxAge' => 0,
]

allowedOrigins, allowedHeaders and allowedMethods can be set to array('*') to accept any value.

Note: Try to be a 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.

Lumen

On Laravel Lumen, load your configuration file manually in bootstrap/app.php:

$app->configure('cors');

And register the ServiceProvider:

$app->register(Barryvdh\Cors\ServiceProvider::class);

Global usage for Lumen

To allow CORS for all your routes, add the HandleCors middleware to the global middleware:

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

Group middleware for Lumen

If you want to allow CORS on a specific middleware group or route, add the HandleCors middleware to your group:

$app->routeMiddleware([
    // ...
    'cors' => \Barryvdh\Cors\HandleCors::class,
]);

Common problems and errors (Pre Laravel 5.3)

In order for the package to work, the request has to be a valid CORS request and needs to include an "Origin" header.

When an error occurs, the middleware isn't run completely. So when this happens, you won't see the actual result, but will get a CORS error instead.

This could be a CSRF token error or just a simple problem.

Note: This should be working in Laravel 5.3+.

Disabling CSRF protection for your API

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

protected $except = [
    'api/*'
];

License

Released under the MIT License, see LICENSE.

laravel-cors's People

Contributors

adamwathan avatar ajthinking avatar anteriovieira avatar barryvdh avatar bencromwell avatar binhqx avatar boonstoppel avatar casperhr avatar cberio avatar codeclown avatar cozylife avatar grahamcampbell avatar honeroku avatar hootlex avatar irazasyed avatar jamiehd avatar joshuajabbour avatar lamoimage avatar lex111 avatar lucasmichot avatar marktinsley avatar martintern avatar nyanlynnhtut avatar omranic avatar pawel-damasiewicz avatar physio avatar rap2hpoutre avatar robbytaylor avatar stefanullrich avatar wolg avatar

Watchers

 avatar  avatar

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.