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

Discussion (1)

Collapse
tiagofrancafernandes profile image
Tiago França

great