Laravel 5.3 CORS with JWT auth - php

I have an issue with Laravel 5.3 CORS. I searched a lot on this issue, and found many recommending barryvdh for CORS. This however didn't work, and I found people mentioning that this could be caused by the use of tymondesigns jwt-auth module. Some suggests bypassing it by setting
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
in the api.php file. This results in responses like:
Failed to load https://example.com/api/v1/members/1: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
In attempt to resolve this issue I added
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
to the above 2 lines. However this left me with a new issue:
PUT https://example.com/api/v1/members/1 403 (Forbidden)
Failed to load https://example.com/api/v1/members/1: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://example.com' is therefore not allowed access. The response had HTTP status code 403.
Any suggestions how to go about this?

If this is only happening on production, be sure to check your nginx configuration files. This is likely due to the following settings:
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
Try commenting these out to see if that fixes the situation, then un-comment one by one, and make adjustments as necessary.

You can use three-way to solve this problem:
1) Use barrvay/laravel-cors
'supportsCredentials' => false,
'allowedOrigins' => ['http://localhost:4200'],
'allowedHeaders' => ['Content-Type','Accept','Authorization'],
'allowedMethods' => ['GET','POST','PUT', 'PATCH', 'OPTIONS', 'DELETE'],
'exposedHeaders' => ['Content-Disposition', 'x-total-count', 'x-filename'],
'maxAge' => 0,
'hosts' => ['*'],
2) Use Chrome Plugin (Moesif CORS) for localhost
3) Build a CORS middleware and putt all of cors header inside it
namespace App\Http\Middleware;
use Closure;
class Cors {
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}

Related

API Rest Laravel 8 Cors

I have an API Rest with Laravel 8.12 and a front-end with VueJS, locally I can connect to the API correctly, but when uploading everything to the server where the system will be, which has "Window Server 2012 R2" installed, when trying to consult the end points the API gives cors error, I tried installing laravel cors plugins, creating a middleware and nothing, it does not work always gives cors error.
Also try using the headers
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Allow: GET, POST, OPTIONS, PUT, DELETE");
I put these in the public/index.php and routes/api.php and it still gives the error.
I do not know if it is the server that is blocking due to some missing configuration, here I do not know completely how it would be done in the ISS.
How could I solve the cors error?

I am getting CORS errors despite setting PHP headers and .htaccess file

I have had a lot of success securely allowing CORS but I have tried with another page and it's not working. I hope someone can tell me what I'm missing. I know that * is insecure, but I'm trying that just to eliminate the site name as a variable.
.htaccess file
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
and the top of my php file:
// Allow from any origin just for testing...
if (isset($_SERVER['HTTP_ORIGIN'])) {
// in production, no *, but using my real domain
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}
When accessing the php file with an ajax request, I receive:
Access to XMLHttpRequest at 'https://sitename.000webhostapp.com/' from origin 'https://samesitename.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
It works in Postman. Here is header info:
Date →Mon, 29 Apr 2019 18:50:03 GMT
Content-Type →text/html; charset=UTF-8
Transfer-Encoding →chunked
Connection →keep-alive
Access-Control-Allow-Origin →*
Access-Control-Allow-Headers →origin, x-requested-with, content-type
Access-Control-Allow-Methods →PUT, GET, POST, DELETE, OPTIONS
Server →awex
X-Xss-Protection →1; mode=block
X-Content-Type-Options →nosniff
X-Request-ID →18341eb6e5c7e5f483d8dd3a3a492b9c
Content-Encoding →gzip
The bigger story is that I'm hosting the main site on firebase which doesn't support PHP, so I put the php files on 000webhostapp.com as a workaround.
In case anyone comes across this post with a similar issue, my resolution was to double check the url!!!
I posted that I was checking
https://sitename.000webhostapp.com/
when I was supposed to reference
https://sitename.000webhostapp.com/php/mail.php
Thanks to #Phil and #emix for forcing me to check the details.

React + Codeigniter Response for preflight is invalid

I have a website that was built using codeigniter MVC but following modern trends I'm trying to create a frontend based on react. I still want to use original codeigniter framework and controllers but instead or rendering views I want it to return plain JSON. Currently I'm stuck on being unable to send requests from react application that runs in debug mode on localhost:3000 to my codeigniter api that is running on apache http://mywebsite:80
this is how I'm initiating request:
fetch("http://mywebsite/Api" + route + '/', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
redirect: 'follow',
body: JSON.stringify(data),
dataType : 'json'
})
This is the error I'm getting in a console:
Failed to load http://mywebsite/ApiAuth/login/: Response for preflight
is invalid (redirect)
My php page sends the following back:
header('Content-Type: application/json;charset=UTF-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: DELETE, HEAD, GET, OPTIONS, POST, PUT');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
header('Access-Control-Max-Age: 1728000');
Console outputs:
Request URL: http://mywebsite/ApiAuth/login/
Request Method: OPTIONS
Status Code: 302 Found
Remote Address: [::1]:80
Referrer Policy: no-referrer-when-downgrade
Was able to fix the issue by setting Apache response headers and redirect method like this:
#Redirect for CORS Preflight request
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
#Set headers to access CORS Requests / allowing localhost only
Header always add Access-Control-Allow-Origin "*"
Header always add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header always add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

Laravel response 405 to OPTIONS requests

In Laravel We must handle preflight requests by middleware or other ways. In my case, I did many but it never solved!
Here are what I tried,
Handle By Middleware
In this case, I did create a new middleware and put this code as handle method.
public function handle($request, Closure $next) {
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); }
and I added this to the $middleware array in kernel.php
Using laravel-cors
I used the laravel-cors library to handle cors but not works too
Adding cors handle codes in public/index.php
I added below codes at top of the public/index.php file,
if (isset($_SERVER["HTTP_ORIGIN"]) === true) {
$origin = $_SERVER["HTTP_ORIGIN"];
$allowed_origins = array(
"https://tapesh.io",
"http://tapesh.io",
"http://my.tapesh.io",
"http://panel.tapesh.io",
);
if (in_array($origin, $allowed_origins, true) === true) {
header('Access-Control-Allow-Origin: ' . $origin);
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: Content-Type, X-Auth-Type, Origin');
}
if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
exit; // OPTIONS request wants only the policy, we can stop here
}
}
Apache config
Also, I checked the apache error logs. the error was something like this,
[Sat Dec 07 07:35:36.678676 2018] [allowmethods:error] [pid 7902:tid
139855840466688] [client 84.417.45.0:4012] AH01623: client method
denied by server configuration: 'OPTIONS' to
/home/main/domains/example.com/private_html/api
I googled that and find out to handle this with apache I should add Require all granted to the Apache 2.4 config file of my domain. I did but not worked!
I must also say, in other projects, I used laravel-cors library and it solved mine.
I really confused about!
try adding the headers in your routes.php file:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
add more Allow-* headers if you want to. but of course, I suggest you use your code in 'Adding cors handle codes in public/index.php' section of your question in routes.php, because that's a safer bet

Allowing cors in artisan serve

Now after starting to learn Angularjs and Laravel 4 I just love the way one can just set up a working development server with just one terminal command without having to set up virtualhosts or anything like that.
However...
I want to develop my frontend seperately so I can utilize the wonderful combination of yeoman and gruntjs and since I really can't do this if I put everything in laravel public folder (or at least I don't know how) this leaves me with the following situation:
I have a frontend grunt server at localhost:9000
And
I have a laravel 4 server at localhost:8000
This will of course mean that in order for Angularjs to talk with Laravel I have to allow CORS. In Apache this is easy: just adding Header add Access-Control-Allow-Origin "localhost:9000" to the directory part of httpd.conf allows this url to communicate with localhost.
Now where should I put this cors configuration when serving stuff via
artisan if its even possible?
Alright found the answer at least one working for me. It would seem I was approaching the problem from the wrong direction since I concentrated on Apache instead of Laravel itself.
In order to allow Cross Origin Response in a development environment via artisan the following code should be inserted in filters.php:
<?php
...
App::before(function($request)
{
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
$statusCode = 204;
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers' => 'Origin, Content-Type, Accept, Authorization, X-Requested-With',
'Access-Control-Allow-Credentials' => 'true'
];
return Response::make(null, $statusCode, $headers);
}
});
App::after(function($request, $response)
{
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
$response->headers->set('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Requested-With');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
return $response;
});
...
Also in case it is relevant I also added 'Access-Control-Allow-Origin' => '*' to Apache configation.
So now I can run my server environment in localhost:8000 and my frontend in localhost:9000 and they can talk to each other without problem.
I faced the same issue. You can find cors configuration in config/cors.php. By default all origins allowed only for api/* routes. You can add your own routes (e.g. oauth) to it like following:
'path' => ['api/*', 'oauth/*']

Categories