Preflight authorization header during CORS on Slim framework - php

Right now i'm having an issue with CORS (cross-origin resource sharing) especially when trying to send authorization to slim api. I've tried to remove the authorization header on jquery, it works like a charm! But i need authorization to pass api key which i have no clue how to bypass the preflight mode (OPTIONS). Here is the javascript code.
$.ajax({
type:'GET',
url:baseApi+'/code/account',
crossDomain:true,
xhrFields:{
withCredentials:true
},
beforeSend:function(xhr){
$overlay.css('display','block');
xhr.setRequestHeader("Authorization",boot._header);
},
complete:function(xhr){
// complete scope
}
});
On slim framework, i have set Access-Control-Allow-Origin with the whitelist origin domain (www.example.com). Here is the complete configuration
if (isset($_SERVER['HTTP_ORIGIN'])) {
if($_SERVER['HTTP_ORIGIN'] == "http://www.example.com"){
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
}
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
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: Authorization, authorization, Content-Type");
}
And here are the complete request and response headers
Response Headers
HTTP/1.1 404 Not Found
Date: Tue, 14 Feb 2017 14:44:34 GMT
Server: Apache/2.4.23 (Unix) OpenSSL/1.0.2h PHP/5.6.24 mod_perl/2.0.8-dev Perl/v5.16.3
X-Powered-By: PHP/5.6.24
Access-Control-Allow-Origin: http://www.example.com
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Authorization, authorization
Content-Length: 514
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html;charset=UTF-8
Request Headers
OPTIONS /code/account HTTP/1.1
Host: api.example.com
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://www.example.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Access-Control-Request-Headers: authorization
Referer: http://www.example.com/account/payout
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,id;q=0.6,ms;q=0.4
Accept: */*
I have tried possible solution from others, but no chance to fix this. Always shown 404 with OPTIONS method called, not GET method like it supposed to.

After researching and investigating, i ended up using CORS middleware for Slim as suggested by #Mika Tuupola. But since i'm using Slim v2, this repo https://github.com/palanik/CorsSlim suitable for me. And if you are using Slim v3, use this repo https://github.com/tuupola/cors-middleware as created by our saviour. Hope it helps!

For Slim Framework 2.4 Version I did a small hack to tackle the Preflight OPTIONS request
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
if($app->request->isOptions()) {
return true;
break;
}
$app->post('/authenticate', 'authenticateUser');
$app->run();
So this will track all OPTIONS requests and return true and it worked for me.
My .htaccess file was like as follows
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "X-Requested-With, Content-Type, Accept, Origin, Authorization"
Header add Access-Control-Allow-Methods "GET, POST, OPTIONS"
Hope this helps.

Related

CORS Error 405 method not allowed with response for preflight does not have HTTP ok status

I've been trying using axios from Vue calling to my API in lumen but it sends options method in place of post because of CORS.
Here is my request details
General
Request URL: http://192.168.1.100/lv_api/code/login
Request Method: OPTIONS
Status Code: 405 Method Not Allowed
Remote Address: 192.168.1.100:80
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, X-
Requested-With
Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin: http://192.168.1.100:8000
Allow: POST
Cache-Control: no-cache, private
Connection: close
Content-Type: text/html; charset=UTF-8
Date: Wed, 03 Oct 2018 06:22:56 GMT
Server: Apache/2.4.18 (Ubuntu)
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: 192.168.1.100
Origin: http://192.168.1.100:8000
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
Tried setting headers but I am not sure about the proper values to be set for the issue.
If I create a method for Options request in my API it works fine but that's not the proper solution to this.
Thanks in advance.
Resolved the issue just by adding following lines in my api code
header('Access-Control-Allow-Origin: your origin');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age:86400');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Accept, Authorization, X-Requested-With');
you can install spatie/laravel-cors for resolve this issue

PHP-AJAX CORS Fails due to Access-Control-Allow-Origin

I am trying to make an AJAX call (CORS) using the below code:
$.ajax({
type: "POST",
url: 'http://localhost/MySpace',
success: function(result) {
console.log(result);
},
error: function() {
console.log("error");
},
});
I am running the above code from:
http://127.0.0.1/Test/index.html
The PHP Code written at http://localhost/MySpace is as below:
<?php
header("Access-Control-Allow-Origin: *");
echo "Hello";
?>
As per my understanding, this should have worked. However I am getting this error:
XMLHttpRequest cannot load http://localhost/MySpace. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1' is therefore not allowed access.
What should I do make this work? Or am I doing something entirely wrong?
As per suggestions to debug the request I tried making a curl request:
curl -i http://127.0.0.1/MySpace/
And in response I can see that Access-Control-Allow-Origin is marked as *:
HTTP/1.1 200 OK
Date: Fri, 13 May 2016 05:59:19 GMT
Server: Apache/2.4.18 (Unix) OpenSSL/1.0.2g PHP/5.6.19 mod_perl/2.0.8-dev Perl/v5.16.3
X-Powered-By: PHP/5.6.19
Access-Control-Allow-Origin: *
Content-Length: 5
Content-Type: text/html; charset=UTF-8
As per the comment I added the below code to my .htaccess:
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"
#Edit:
This is my Response Header:
HTTP/1.1 301 Moved Permanently
Date: Fri, 13 May 2016 09:26:44 GMT
Server: Apache/2.4.18 (Unix) OpenSSL/1.0.2g PHP/5.6.19 mod_perl/2.0.8- dev Perl/v5.16.3
Location: http://localhost/elasticservice/
Content-Length: 240
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1
This is my request header:
POST /elasticservice HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 0
Cache-Control: max-age=0
Accept: */*
Origin: http://127.0.0.1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36
Referer: http://127.0.0.1/test/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,hi;q=0.6
You have allowed CORS Origin, so for access cross domain 3 headers (Origin, Methods, Headers) compulsory, see below sample 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");
#update: you can try this solution
header('Access-Control-Allow-Origin: *');
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
$headers=getallheaders();
#$ACRH=$headers["Access-Control-Request-Headers"];
header("Access-Control-Allow-Headers: $ACRH");
}
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
try the following url:
$.ajax({
type: "POST",
url: 'http://127.0.0.1/MySpace',
success: function(result) {
console.log(result);
},
error: function() {
console.log("error");
},
});

PHP Cross-Origin Request Blocked

just wanted to find a solution to this. I am within System A and I make the following call
$("#page-form").submit(function(event){
$.ajax({
type: "POST",
url: "https://someOtherUrl/process.php",
data: {
'mobNumber': $("#mobile").val()
}
}).done(function (response) {
alert(response);
});
})
Now this makes a call to a PHP file on another server. This PHP file does nothing at the moment, I simply have
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
var_dump("1");
However I am getting a cross origin request blocked error. Why would this be happening?
As a side note, I have no access to the server running System A, so it has to be done on my server where the PHP file sits.
Thanks
Update
Server seems to have this
Response headers
Cache-Control no-cache
Connection Keep-Alive
Content-Type text/html; charset=utf-8
Date Thu, 25 Jun 2015 12:31:50 GMT
Expires Thu, 25 Jun 2015 12:31:50 GMT
Keep-Alive timeout=5, max=99
Pragma no-cache
Server Apache
Transfer-Encoding chunked
Vary Accept-Encoding
x-ua-compatible IE=edge
Request headers
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection keep-alive
User-Agent
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0
Try this in the .htaccess file present at the root folder on https://someOtherUrl/ :
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>

AngularJS, PHP Restful Cors issue

I have an issue trying to make an $http call to my rest php server.
I'm doing cross domain calls from the client to the backend.
From within my Angular app this is how the $http service is configured:
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('httpResponseInterceptor');
$httpProvider.interceptors.push('httpTimeStampMarker');
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
delete $httpProvider.defaults.headers.common['Content-Type, X-Requested-With'];
}])
This is how the actual $http.post() is configured:
// Set the headers
var headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT',
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': '*'
};
return $http({
method: "POST",
url: base_url,
data: $.param(args),
headers: headers
})
.success(function(data, status) {
})
.error(function(data, status) {
});
This is the .htaccess of the server:
# Cors
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Methods"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
The preflight request goes fine:
**Request headers:**
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:access-control-allow-origin, accept, access-control-allow-methods, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:***
Origin:***
Referer:***
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36
**Response headers**
Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Methods
Access-Control-Allow-Methods:PUT, GET, POST, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Allow:OPTIONS,GET,HEAD,POST
Connection:Keep-Alive
Content-Length:0
Content-Type:httpd/unix-directory
Date:Fri, 26 Dec 2014 07:12:24 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.9 (Unix) PHP/5.6.2
However the actual post request fails:
XMLHttpRequest cannot load http://***/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '***' is therefore not allowed access. The response had HTTP status code 404.
These are the request and response headers:
**Request headers**
Accept:*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Access-Control-Allow-Methods:POST, GET, OPTIONS, PUT
Access-Control-Allow-Origin:*
Connection:keep-alive
Content-Length:130
Content-Type:application/x-www-form-urlencoded
Host:***
Origin:http://***
Referer:***
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36
**Response headers**
Connection:Keep-Alive
Content-Length:198
Content-Type:text/html; charset=iso-8859-1
Date:Fri, 26 Dec 2014 07:12:24 GMT
Keep-Alive:timeout=5, max=99
Server:Apache/2.4.9 (Unix) PHP/5.6.2
I'm obviously missing some headers in the response off the post request.
However the issue it's failing on does work in the preflight request. I've tried adding some headers in the index.php of the rest server, but the request doesn't arrive there and gets stuck earlier (I'm guessing when the .htaccess is loaded).
What am I missing here?
After a few hours I finally found it out.
My .htaccess:
# Cors
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Access-Control-Allow-Origin"
Header always set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
The hint #Alexey Rodin gave was almost the right one. Instead of changing "add" to "set" it should be set to "always set".
This site helped me out:
Regarding AngularJS, I can confirm that no other settings are needed for CORS to work.
So Angular's $http does not need the be changed with headers or so, the default settings should work with the .htaccess entries stated above.
Try to use set instead add on your .htaccess
Header set Access-Control-Allow-Origin "*"
See more here

Cross-domain AJAX not working PHP

I have tried to implement a cross-domain AJAX request, based on this answer.
http://jsfiddle.net/PXSMQ/1/
I have added the following headers:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');
header("Access-Control-Allow-Headers: x-requested-with");
header('Access-Control-Allow-Headers: x-csrf-token');
But I still get this error:
XMLHttpRequest cannot load http://www.belardi.ro/userTrack/addData.php. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.
The Access Control headers have to be configured on the server that you're sending your request to. You can't set them yourself. If the server you're sending your request to is not configured appropriately you won't be able to make these requests.
Those headers are not appearing in the response from addData.php:
david#raston ~ $ curl -i -d 'some=json' http://www.belardi.ro/userTrack/addData.php
HTTP/1.1 200 OK
Date: Wed, 19 Jun 2013 10:12:35 GMT
Server: LiteSpeed
Connection: close
X-Powered-By: PHP/5.2.14
Content-Type: text/html
Content-Length: 16
Vary: User-Agent
Invalid page url~ :

Categories