86

I'm new to Laravel and am doing some Laravel 5.3 Passport project with OAuth2.0 password grant. When I curl the API with the params it responds with token. However, in browser it needs an additional security that the endpoint should add because my request is coming from localhost while the API is located in my VM. Here's the error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 400.

I know what the issue is but I don't know where to put to include that header since this is a third party app.

Thank you in advance experts. Please help.

1

17 Answers 17

206

The simple answer is to set the Access-Control-Allow-Origin header to localhost or *. Here's how I usually do it:

Create a simple middleware called Cors:

php artisan make:middleware Cors

Add the following code to app/Http/Middleware/Cors.php:

public function handle($request, Closure $next)
{
    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}

You can replace the * with localhost or keep it as it is.

Next step is to load the middleware. Add the following line to the $routeMiddleware array in app/Http/Kernel.php.

'cors' => \App\Http\Middleware\Cors::class, 

And the final step is to use the middleware on the routes to which you want to set the access origin headers. Assuming you are talking about the new api routes in laravel 5.3, the place to do it is app/Providers/RouteServiceProvider.php, inside the mapApiRoutes() function (you can remove or comment the previous code of the function):

    Route::group([
        'middleware' => ['api', 'cors'],
        'namespace' => $this->namespace,
        'prefix' => 'api',
    ], function ($router) {
         //Add you routes here, for example:
         Route::apiResource('/posts','PostController');
    });
6
  • 9
    I'm trying to make this work too (see here) but for some reason only the GET requests work. Any idea why POST is not working with my setup? Also.. the order of the middleware seems to matter. Oct 28, 2017 at 15:07
  • I am making ajax call and this solution does not work for me, any suggestion? Dec 29, 2017 at 14:01
  • 4
    Very clear for my Laravel 5.6 and Angular 5 Application. Thanks! Mar 20, 2018 at 3:13
  • 2
    Instead of the last step just add this at the end of your routes: Route::get('/url','controller@function') -> middleware('cors'); May 2, 2019 at 6:49
  • Laravel 8 already has cors middleware included. But not working for me either (dont need auth since no users are stored in db)
    – trainoasis
    Dec 2, 2020 at 14:50
72

The simple answer is to set the Access-Control-Allow-Origin header to localhost or *. Here's how I usually do it:

Add the following code to bootstrap/app.php:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');

WARNING: Only do this in your developer environment.

7
  • 2
    i think it would be something more like this: header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: *'); header('Access-Control-Allow-Headers: Origin, X-Requested-With,Authorization, Content-Type, Accept'); Jun 27, 2019 at 14:15
  • 4
    Would this leave your application open to attacks as you are also allowing everyone to Post to your entire application? Nov 19, 2019 at 15:48
  • 1
    Never do this , it means any one can Post data to your application.
    – Jobin
    Nov 19, 2020 at 5:54
  • 2
    for development purpose only, it works thank you Nov 30, 2020 at 10:31
  • 1
    Finally something that works for Laravel 8..
    – Gass
    Nov 21, 2021 at 17:09
25

You could also use the great laravel-cors package by barryvdh.

After you have the package installed, the easiest way to get CORS support for all your routes is to add the middleware like this in Http/Kernel.php:

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Barryvdh\Cors\HandleCors::class,
];

If you dont want to have CORS support on all your routes you should make a new OPTIONS route for /oauth/token and add the cors middleware to that route only.

Edit for Laravel 8

Laravel 8 already has CORS Support built in - HandleCors middleware is defined in your global middleware stack by default and can be configured in your application's config/cors.php config file.

If you update your Laravel application be sure to change out barryvdh's package with the supplied middleware: \Fruitcake\Cors\HandleCors::class

1
  • For now, it should \Fruitcake\Cors\HandleCors::class, instead of \Barryvdh\Cors\HandleCors::class. Docs
    – ibnɘꟻ
    Feb 16, 2021 at 6:51
10

For those who didn't solve the problem setting route middleware in App\Http\Kernel, try to set global middleware. In App\Http\Middleware\Cors:

public function handle($request, Closure $next)
{
    return $next($request)->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}

In App\Http\Kernel:

protected $middleware = [
    ...
    \App\Http\Middleware\Cors::class,
];
2
  • This worked!!! Earlier had Cors middleware in as route middleware which didn't help in resolving OPTIONS method requests(Preflight). Setting Cors as global middleware handled all incoming requests including Preflight ones. Adding to the answer, if allow-credentials is true, setting allow-origin to * won't work. Origin will have to be specific in case of Allow-Credentials as true. The origin can be fetched from the request headers and then be added to response header.
    – 1nfern0
    Dec 10, 2021 at 7:00
  • This method worked for me. If it's not working, you can try in incognito page. Aug 26, 2022 at 21:06
7

Create A Cors.php File in App/Http/Middleware and paste this in it. ☑

<?php

namespace App\Http\Middleware;

use Closure;


class Cors {    public function handle($request, Closure $next)
    {
        header("Access-Control-Allow-Origin: *");
        //ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods' => 'POST,GET,OPTIONS,PUT,DELETE',
            'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization',
        ];
        if ($request->getMethod() == "OPTIONS"){
            //The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return response()->json('OK',200,$headers);
        }
        $response = $next($request);
        foreach ($headers as $key => $value) {
            $response->header($key, $value);
        }
        return $response;

    } }

And Add This Line In Your Kernel.php after the "Trust Proxies::Class" Line.

\App\Http\Middleware\Cors::class,

Thats It You have Allowed All Cors Header. ☑

4

After https://github.com/fruitcake/laravel-cors I had to change in cors.php file as below

     * Sets the Access-Control-Allow-Credentials header.
     */
    'supports_credentials' => true,
1
  • After setting above key value 'supports_credentials' => true in config/cors.php file in laravel, Clear your config cache (php artisan config:clear), route cache (php artisan route:clear) and normal cache (php artisan cache:clear). It will work fine for the defined path in the cors.php file.
    – ANIL PATEL
    Oct 17, 2020 at 11:18
3

Be careful, you can not modify the preflight. In addition, the browser (at least chrome) removes the "authorization" header ... this results in some problems that may arise according to the route design. For example, a preflight will never enter the passport route sheet since it does not have the header with the token.

In case you are designing a file with an implementation of the options method, you must define in the route file web.php one (or more than one) "trap" route so that the preflght (without header authorization) can resolve the request and Obtain the corresponding CORS headers. Because they can not return in a middleware 200 by default, they must add the headers on the original request.

2

Just add this to your code Controller

return response()->json(compact('token'))->header("Access-Control-Allow-Origin",  "*");
2
  • Please put your answer always in content instead of simply pasting code, thanks! Aug 6, 2019 at 9:31
  • can you explain why?
    – jhon
    Jun 30, 2020 at 4:09
2

If you've applied the CORS middleware and it's still not working, try this.

If the route for your API is:

Route::post("foo", "MyController"})->middleware("cors");

Then you need to change it to allow for the OPTIONS method:

Route::match(['post', 'options'], "foo", "MyController")->middleware("cors");
0
2

If for some reason it's still not working. First option for Laravel The second option for any application

FIRST OPTION:

  1. As in the example above, we create middleware

     php artisan make:middleware Cors
    
  2. Add the following code to app/Http/Middleware/Cors.php:

     public function handle($request, Closure $next) 
     {
         return $next($request)
             ->header('Access-Control-Allow-Origin', '*')
             ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
             ->header('Access-Control-Allow-Headers', 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'); 
     }
    

Look closely, the amount of data in the header ->header('Access-Control-Allow-Headers',

  1. Step three, add middleware to $routeMiddleware array in app/Http/Kernel.php

     protected $routeMiddleware = [
         ....
         'cors' => \App\Http\Middleware\Cors::class,
     ];
    

SECOND OPTION:

  1. Open the nginx.conf settings for your domain.

     sudo nano /etc/nginx/sites-enabled/your-domain.conf
    
  2. Inside the server settings server { listen 80; .... } please add the following code:

     add_header 'Access-Control-Allow-Origin' '*';
     add_header 'Access-Control-Allow-Credentials' 'true';
     add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
     add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';
    
1
  • First option was my solution to get assets back enabling cors Sep 18, 2021 at 22:39
1

Few steps to add Access-Control-Allow-Origin header to localhost or *.

Step 1: Create Cors middleware :

php artisan make:middleware Cors

Step 2: Set header in Cors middleware like this

public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response->headers->set('Access-Control-Allow-Origin' , '*');
        $response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
        $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');

        return $response;
    }

Step 3: We need to add Cors class in app/Http/Kernel.php

 protected $middleware = [
        ....
        \App\Http\Middleware\Cors::class,
    ];

Here no needed to check any middleware because we add Cors class in $middleware in app/Http/Kernel.php

1

Working Solution

Step 1: Create Cors middleware

php artisan make:middleware Cors

Step 2: Set header in Cors middleware inside handle function

return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

Step 3: Add Cors class in app/Http/Kernel.php

protected $routeMiddleware = [
    ....
    'cors' => \App\Http\Middleware\Cors::class,
];

Step 4: Replace mapApiRoutes in app/providers/routeServiceProvider.php

Route::prefix('api')
         ->middleware(['api', 'cors'])
         ->namespace($this->namespace)
         ->group(base_path('routes/api.php'));

Step 5: Add your routes in routes/api.php

Route::post('example', 'controllerName@functionName')->name('example');
1

You don't need do anything extra. Laravel already have inbuilt provision - read from here https://stackoverflow.com/a/70361284/2612926

0

Just add this to your view:

<?php header("Access-Control-Allow-Origin: *"); ?>
1
0

I am using Laravel 8 and just installed the fruitcake/laravel-cors and use it in app/Http/Kernel.php like blow:

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

note : add it to end of array like me

0

You can do it easily by adding headers in bootstrap/app.php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');
0

Laravel since version ^7.0 comes out of the box with CORS enabled by default. You don't need to add anything.

Below is the default configuration:

config/cors.php

'paths' => ['api/*', 'sanctum/csrf-cookie'],

'allowed_methods' => ['*'],

'allowed_origins' => ['*'], //This line means allow origin

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => false, 

];

Not the answer you're looking for? Browse other questions tagged or ask your own question.