Reputation: 1902
I have a domain_A running Laravel 5.8 engine to return API on web route. It must check origins to let serve just a few domains, included domain_B.
Barryvdh/laravel-cors
I installed barryvdh/laravel-cors by composer and configured it globally updating the Kernel.php. This should works on web route too.
kernel.php
protected $middleware = [
...
\Barryvdh\Cors\HandleCors::class,
];
Then I config the Laravel Cors using the standard configuration as test to allow any domain.
/config/cors.php
return [
'supportsCredentials' => false,
'allowedOrigins' => ['http:www.domain_b.com','https:www.domain_b.com','http:domain_b.com'],
'allowedHeaders' => ['Access-Control-Allow-Origin', 'X-CSRF-TOKEN', 'Content-Type', 'X-Requested-With'],
'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT', 'DELETE']
'exposedHeaders' => [],
'maxAge' => 0,
];
The axios config is:
(domain_a)/ Repository.js
import axios from 'axios/index';
const baseDomain = "https://domain_a";
const baseURL = `${baseDomain}`;
let withCredentials = false;
const token = document.head.querySelector('meta[name="csrf-token"]');
const headers = {
'X-CSRF-TOKEN': token.content,
'Access-Control-Allow-Origin': '*',
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json',
};
export default axios.create({
baseURL,
withCredentials: withCredentials,
headers: headers
});
GET requests are filtered as well, PUT request return a 419 error why? I have set 'allowedMethods' => ['*'] so it should work... what I'm missing?
[EDIT]
ON debug I got this error right now...
message: "CSRF token mismatch."
Why POST doesn't get the header Token?
I tried to pass the POST token also like this:
const token = document.head.querySelector('meta[name="csrf-token"]');
const options = {
headers: {
'Authorization' : 'bearer '+token.content,
}
};
const body = {};
return Repository.post(`${resource}/${$playerId}/${$cozzaloID}`, body, options)
Preflight Header Response
Access-Control-Allow-Headers: authorization, content-type, x-requested-with, x-csrf-token
Access-Control-Allow-Methods: POST
Access-Control-Allow-Origin: http://www.******.**
Cache-Control: no-cache, private
Connection: Keep-Alive
Content-Length: 0
Content-Type: text/html; charset=UTF-8
Date: Mon, 01 Jul 2019 05:14:22 GMT
Keep-Alive: timeout=5, max=98
Server: Apache
X-Powered-By: PHP/7.1.30, PleskLin
Header Response:
Access-Control-Allow-Origin: http://www.xxxxxxx.xx
Cache-Control: no-cache, private
Connection: Keep-Alive
Content-Type: application/json
Date: Mon, 01 Jul 2019 05:14:22 GMT
Keep-Alive: timeout=5, max=97
Server: Apache
Transfer-Encoding: chunked
Vary: Origin,Authorization
X-Powered-By: PHP/7.1.30, PleskLin
Header Request:
Provisional headers are shown
Accept: application/json, text/plain, */*
Authorization: Bearer jW6pFcVlkKyApCxtZIlfaHDPMSFWCWcbnPPTQ7EJ
Content-Type: application/json
Origin: http://www.xxxxxxx.xx
Referer: http://www.xxxxxx.xx/players/739
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100
Safari/537.36
X-CSRF-TOKEN: jW6pFcVlkKyApCxtZIlfaHDPMSFWCWcbnPPTQ7EJ
X-Requested-With: XMLHttpRequest
Note about token: It should be OK because it is the same as another GET request done in the same task.
Upvotes: 5
Views: 10604
Reputation: 650
in the address
vendor/fruitcake/laravel-cors/src/HandleCors.php
comment this
// Check if we're dealing with CORS and if we should handle it
if (! $this->shouldRun($request)) {
return $next($request);
}
Upvotes: 0
Reputation: 446
Please use routes/api.php for apis routing, don't use the routes/web.php for api.
If you want to use sub-domain then do required changes in following file:
app/Providers/RouteServiceProvider.php
Original:
protected function mapApiRoutes() {
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
Updated:
protected function mapApiRoutes() {
Route::domain('api.' . env('APP_URL'))
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
Upvotes: 5