Monday, March 28, 2016

Adding crossdomain policy security

Creating .htaccess file in your application root folder

<FilesMatch "\.(mpd||m4s|m3u8|jpg|png)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
  </IfModule>
</FilesMatch>


Add the XORS request middleware in laravel
<?php namespace App\Http\Middleware;
use Closure;//use Symfony\Component\HttpFoundation\Response;
class Cors {
    /**     * Handle an incoming request.     *     * @param  \Illuminate\Http\Request  $request     * @param  \Closure  $next     * @return mixed     */    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'        ];        if($request->getMethod() == "OPTIONS") {            // The client-side application can set only headers allowed in Access-Control-Allow-Headers            return Response::make('OK', 200, $headers);        }
        $response = $next($request);        foreach($headers as $key => $value)            $response->header($key, $value);        return $response;    }
//    public function handle($request, Closure $next)//    {//        $content = $next($request);//        return ( new Response($content) )->header('Access-Control-Allow-Origin' , '*')//            ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')//            ->header('Access-Control-Allow-Headers', 'Content-Type, X-Auth-Token, Origin');//    }
}

In Kernel.php
protected $middlewareGroups = [    'web' => [        
        \App\Http\Middleware\Cors::class,
    ],

No comments:

Post a Comment