DEV Community

keikesu0122
keikesu0122

Posted on

A simple way to enable CORS on Laravel

What is CORS?

CORS stands for Cross Origin Resource Sharing. Origin consists of protocol, domain and port number such as https://hogehoge.com:443. Therefore, CORS means allowing an web application on a certain origin (e.g. https://hogehoge.com) to access an web application on a different origin (e.g. https://fugafuga.com).

Why is CORS necessary?

In order to prevent cross site scripting (XSS) and cross site request forgeries, JavaScript's asynchronous communication such as Ajax follows the same origin policy, which bans access to a different origin. Without CORS configuration, web applications can not access a different origin.

What is required to enable CORS?

The simplest method to enable CORS is to add Access-Control-Allow-Origin:* to the response header from WEB servers, which allows CORS from any source. If you want to limit the source, you should specify the domain in the configuration such as Access-Control-Allow-Origin:https://hogehoge.com. You should note that a domain has to be specified if an http request includes cookie information.

How to enable CORS on Laravel

You can use an middleware that adds Access-Control-Allow-Origin to an http response header.

  1. create an middleware
$ php artisan make:middleware Cors
Enter fullscreen mode Exit fullscreen mode

2.Edit the middleware

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')

    }
}
Enter fullscreen mode Exit fullscreen mode

3.Add the middleware to Kernel.php

protected $routeMiddleware = [
        'auth'          => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic'    => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings'      => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can'           => \Illuminate\Auth\Middleware\Authorize::class,
        'guest'         => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'signed'        => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle'      => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'cors'          => \App\Http\Middleware\Cors::class, // added
    ];
Enter fullscreen mode Exit fullscreen mode

4.Set the middleware to routes

Route::middleware(['cors'])->group(function () {
    Route::post('/hogehoge', 'Controller@hogehoge');
});
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
abrahambrookes profile image
Abraham Brookes

This looks like it allows everything through your CORS, which might not be the intent. Aren't you better off having an allow list for authorized domains?

Have a look at config/cors.php - you can pass an array of allowed origins in there, I reckon that's going to be more secure

Collapse
 
amfarhad33 profile image
Mohammad Farhad

This doesn't work for me. Can anyone please help me?

Show me the following error....

Access to XMLHttpRequest at 'api.myguardianbd.com/api/test/myGu...' from origin '127.0.0.1:3000' 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.

Collapse
 
moose_said profile image
Mostafa Said

Does that have any security concerns when app goes in production?

Collapse
 
binyamkpaul profile image
Binya

i cant find config /cors.php file on my Laravel 8 project is there any option to to create

Collapse
 
tiagofrancafernandes profile image
Tiago França

great