Adding a CORS handler

We will be building an application that will serve up JSON responses to requests. A separate application running on a separate domain will consume those responses and make requests to the application. Having a web application that sends requests from a different domain to the webserver itself is a configuration that represents a security risk. This is called Cross-Origin Resource Sharing. In order that the default situation be secure, there are barriers to Cross-Origin Resource Sharing both at the Server and at the Browser level.

To overcome these barriers we need to introduce some middleware that will handle CORS requests. Ideally, we would set up a proper authentication system as this approach introduces a security threat. The approach below will do while we're just getting started with REST Apis. Save the following code as the file app\Http\Middleware\CorsMiddleware.php

<?php namespace App\Http\Middleware;
class CorsMiddleware 
{
     public function handle($request, \Closure $next)
     {
         //Intercepts OPTIONS requests
         if($request->isMethod('OPTIONS')) {
             $response = response('', 200);
         } else {
             // Pass the request to the next middleware
             $response = $next($request);
         }
         // Adds headers to the response
         $response->header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, PATCH, DELETE');
         $response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers'));
         $response->header('Access-Control-Allow-Origin', '*');
         // Sends it
         return $response;
    }
}

Now, in order to register this middleware and start it working within the application add the following lines to bootstrap\app.php

$app->middleware([
       App\Http\Middleware\CorsMiddleware::class
    ]);

Place this in the Register Middleware section of the bootstrap file as follows

Now any requests coming through from a different domain will be permitted through and any responses sent back will have the correct expected headers satisfying the browser making the request.

Leave a Reply