AngularJS, PHP Restful Cors issue - php

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

Related

getting different php session ID evey request I make. angular front end

So I have my PHP on a server, and my angular app locally.
for every request I make, I am getting back a different PHP session id in my network tab. Because of this I cannot test my session cookie as it doesn't exist.
When I bundle the app and put it on the server (same server as php files) then the sessionID is the same, So I am only having this issue locally.
I have added the correct CORS on my php file (just above session_start()) and I am sending withCredentials: true with my request, yet the session is always different.
Is there anything I need to look out for?
I am somewhat a PHP novice and more experienced in Angular so any help is appreciated.
Angular post request:
loginSession(form: string) {
const options = {
headers: new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8'),
withCredentials: true
}
return this.httpClient.post<any>(`${this.SERVER}/function.php`, form, options);
}
Response Headers:
access-control-allow-credentials: true
access-control-allow-headers: Content-Type
access-control-allow-methods: POST, GET, OPTIONS, DELETE, PUT
access-control-allow-origin: http://localhost:4200
cache-control: no-store, no-cache, must-revalidate
content-type: text/html; charset=UTF-8
date: Wed, 15 Jan 2020 08:44:27 GMT
expires: Thu, 19 Nov 1981 08:52:00 GMT
pragma: no-cache
server: Apache
status: 200
vary: Accept-Encoding,User-Agent
x-content-encoding-over-network: gzip
Request Headers:
:authority: mysite.com
:method: POST
:path: /function.php
:scheme: https
accept: application/json, text/plain, */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cache-control: no-cache
content-length: 68
content-type: application/json; charset=UTF-8
cookie: PHPSESSID=93cfc63e3b04eb7bf6f633ae1b11fba7
origin: http://localhost:4200
pragma: no-cache
referer: http://localhost:4200/
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36
Thank you
Possibly your request is not sending cookies with the request. Php requires client side cookies to maintain the session.
Share your code to provide a better answer. But for time being you should made the request with, withCredentials option set to true.
let options = new RequestOptions({ headers: headers, withCredentials: true });
this.http.post(url, data, options)

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

Preflight authorization header during CORS on Slim framework

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.

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>

Categories