Laravel CORS for static assets - laravel

I am making a video playlist with ffmpeg with laravel but when I want to get a playlist from a public storage as a static asset, it shows Access-Control-Allow-Origin error. I have tried many ways but it did not solve.
I have used this:
namespace App\Http\Middleware;
use Closure;
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With'
];
if ($request->isMethod('OPTIONS'))
{
return response()->json('{"method":"OPTIONS"}', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
{
$response->header($key, $value);
}
return $response;
}
}
Also this in the .htaccess:
Header set Access-Control-Allow-Origin "*"
also this
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
and so on

Related

how to fix Cors error on vue cli to laravel api

I have a project that is currently using Vue cli on localhost:8080 then it request to my laravel api at api.sched.local but it gives me a error CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I'm using laravel 8 so it has already a config/cors and this is inside it
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
and on my axios instance
import axios from 'axios'
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
axios.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.headers.post['Content-Type'] ='application/json;charset=utf-8';
axios.defaults.headers.common['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept';
const defaultOptions = {
headers: {},
}
// var isDevelopment = true;
const instance = axios.create(defaultOptions);
export default instance
I've been stuck on this CORS error for 2 days thanks
NOTE: I am also using laravel passport I dont know if this affect something
I also tried this way but read about some where that you have to add a middleware for cors.So i have added a cors middleware in my project.
<?php
namespace App\Http\Middleware;
use App\Language;
use Closure;
use Illuminate\Support\Facades\App;
class Cors
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$IlluminateResponse = 'Illuminate\Http\Response';
$SymfonyResponse = 'Symfony\Component\HttpFoundation\Response';
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET, PUT, POST, DELETE, PATCH',
'Access-Control-Allow-Headers' => 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Authorization, Access-Control-Request-Headers',
'Access-Control-Allow-Credentials' => 'true',
];
if ($response instanceof $IlluminateResponse) {
foreach ($headers as $key => $value) {
$response->header($key, $value);
}
return $response;
} else if ($response instanceof $SymfonyResponse) {
foreach ($headers as $key => $value) {
$response->headers->set($key, $value);
}
return $response;
}
return $next($request)
->header('Access-Control-Allow-Origin','*')
->header('Access-Control-Allow-Methods','GET, POST, PUT, DELETE, OPTIONS');
}
}
In App\Http\kernel.php =>
$routeMiddleware you can add it => [
'cors' => \App\Http\Middleware\Cors::class
]
Also use this middleware in you api.php.
The same question related to laravel 5 is here for more details :
Laravel 5.1 API Enable Cors

Vue 2 + Laravel 6 error (Access-Control-Allow-Origin)

I was creating my first project between Vue 2 and Laravel 6, I could read information from the API through GET, but I was trying to send a CSV file from the frontend http://localhost/8080 to the backend http://127.0.0.1:8000, but I get the following message
Here I get a cors error, which I have reported and I have seen that it is because they are from different servers
My request from Vue is the following:
axios
.post("http://127.0.0.1:8000/api/import", this.file, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then(function (response) {
console.log(response);
console.log("SUCCESS!!");
})
.catch(function (error) {
console.log(error);
});
The route of my Laravel has the following line
Route::group(['middleware' => 'cors'], function () {
Route::apiResource("naves", "StarwarsController");
Route::post('import', 'StarwarsController#import');});
In the controller I have the following code
public function import(Request $request)
{
return var_dump($request);
$request->file('images');}
And about CORS I have the following information
Cors.php
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', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}
}
and Kernel.php
protected $middleware = [
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\Cors::class
];
protected $routeMiddleware = [
'auth' => \App\Http\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,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'cors' => \App\Http\Middleware\Cors::class,
];
If you could help me I would appreciate it a lot!
Solution:
$origin = (isset($_SERVER['HTTP_ORIGIN'])) ? $_SERVER['HTTP_ORIGIN'] : '*';
header('Access-Control-Allow-Origin: ' . $origin);
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Credentials: true');
header('Content-Type: text/html; charset=UTF-8');
if ($this->input->server('REQUEST_METHOD') == 'OPTIONS') {
header('Access-Control-Allow-Headers: authorization, content-type');
echo json_encode(array());
exit;
}

Cors issues only when send headers

I have vueJS running on http://localhost:8080 and Lumen API running on http://stockprise.test/ . I want to do the following request from vueJS to API:
async log() {
await fetch("http://stockprise.test/login", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({email:'test#gmail.com',password:'pass123'})
}).then(
function(response) {
return response.text();
},
function(error) {
error.message;
}
);
}
but then I get the following error:
This is the code for Cors in lumen
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$IlluminateResponse = 'Illuminate\Http\Response';
$SymfonyResopnse = 'Symfony\Component\HttpFoundation\Response';
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, PATCH, DELETE',
'Access-Control-Allow-Headers' => 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Authorization , Access-Control-Request-Headers',
];
if($response instanceof $IlluminateResponse) {
foreach ($headers as $key => $value) {
$response->header($key, $value);
}
return $response;
}
if($response instanceof $SymfonyResopnse) {
foreach ($headers as $key => $value) {
$response->headers->set($key, $value);
}
return $response;
}
return $response;
}
}
And i call the Middleware in the bootstrap/app.php middlewareApp of lumen:
$app->middleware([
App\Http\Middleware\CorsMiddleware::class
]);
When I remove the headers in fetch it works perfectly but it sends the data in the form application/x-www-form-urlencoded so i have to add the "Content-type":"application/json" ... Any help ?
This code i have tried in Lumen and working fine
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With',
];
if ($request->isMethod('OPTIONS')) {
return response()->json('{"method":"OPTIONS"}', 200, $headers);
}
$response = $next($request);
foreach ($headers as $key => $value) {
$response->header($key, $value);
}
return $response;

Access to XMLHttpRequest at 'abc.com' from origin 'xyz.com' has been blocked by CORS policy No 'Access-Control-Allow-Origin'

i have tried cors middleware and similiar laravel packages its , but cant access outside url , some body can give good solution
kernel.php
\App\Http\Middleware\Cors::class,
Cors Middlware
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;
}

Why Laravel middleware works for single routes but not group of routes

I have added a CORS middleware and it works fine for single routes :-
Route::get('example', ['middleware' => 'cors', function(){
return Response::json(array('name' => 'Steve Jobs', 'company' => 'Apple'));
}]);
But when I apply it to group of routes, it gives error in console :-
(index):1 XMLHttpRequest cannot load http://jotdot.mysite.com/api/authenticate.
Response to preflight request doesn't pass access control
check: No 'Access-Control-Allow-Origin' header is present on
the requested resource. Origin 'http://jotdotfrontend.mysite.com' is
therefore not allowed access.
My group of routes :-
Route::group(['middleware' => 'cors'], function () {
Route::group(['prefix' => 'api'], function()
{
Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
Route::post('authenticate', 'AuthenticateController#authenticate');
});
});
Cors.php
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;
return $next($request);
}
}
I am following https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps and trying to set up backend and frontend on different domains.
Thanks
The problem is that route-based middleware were never applied on OPTIONS request for autogenerated resource-based routes ('cause Route::resource(...) doesn't generate routes for options method?).
So, put yours cors middleware inside global middleware group in app/Http/Kernel.php, just before VerifyCsrfToken middleware:
/**
* The application's global HTTP middleware stack.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Ankh\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\CORS::class, // here it is
\App\Http\Middleware\VerifyCsrfToken::class,
];
And entirely remove it from routes.php, like:
// Route::group(['middleware' => 'cors'], function () {
Route::group(['prefix' => 'api'], function() {
Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
Route::post('authenticate', 'AuthenticateController#authenticate');
});
//});
You can try this:
Route::group(['prefix' => 'api', 'middleware' => 'cors'], function()
{
Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
Route::post('authenticate', 'AuthenticateController#authenticate');
});
Try like this,
Route::group([ 'prefix' => 'api', 'middleware' => 'App\Http\Middleware\CORS'], function() {
Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
Route::post('authenticate', 'AuthenticateController#authenticate');
});
Your origin header isn't in your headers array. Instead of setting your origin header using header(), try adding it with your other access control headers like this:
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Origin'=> '*',
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];

Resources