Symfony 2.5 and Angular $http - php

I have some problem when I'm using $http with my API that I've written using Symfony. When I'm using $http.get at server side I'm adding a header to response : Access-Control-Allow-Origin and everything works and I can get required data from server. But when I'm using $http.post and adding this header , nothing works.
$http.post('http://myhost.loc/posts', {data:'Test string'}).success(function(data, status){
console.log(data);
}).error(function(data, status){
console.log(status);
});
And I get an error :
OPTIONS http://myhost.loc/posts and
No 'Access-Control-Allow-Origin' header is present on the requested resource.
I don't understand why this doesn't work.

its a CORS problem first of all enable CORS on your angular app by
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
A server supporting CORS must respond to requests with several access control headers:
• Access-Control-Allow-Origin *

Before sending a cross domain request, there is a preflight request sent with the OPTIONS method.
The purpose of that preflight request is to check if the ressource is reachable
You can try that in your apache .htaccess
<ifModule mod_headers.c>
Header always set Access-Control-Allow-Origin: "*"
Header always set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "origin, x-requested-with, content-type"
</ifModule>

Related

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"

Cross domain AJAX request failing

I'm trying to make a cross domain ajax request i have set the PHP headers on the receiving end and set the jQuery AJAX request but for some reason it works then you refresh the page and it fires a cors origin error with a response code of 503 which from my research its caused by CORS.
I have followed some instructions from here How do I send a cross-domain POST request via JavaScript?
Headers for api.mydomain.co.uk
header('Access-Control-Allow-Origin: https://mydomain.co.uk');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
jQuery for mydomin.co.uk
$.ajax({
type: 'POST',
url: "//api.mydomain.co.uk/application/mp/basket",
crossDomain: true,
xhrFields:{withCredentials: true},
data: {Route: "ItemCount"},
success: function(data) {
$('.count').text(data);
}
});
Browser Response
It turns out that some Plesk installations are a bit buggy and the 503 error comes from the proxy_fcgi apache process.
To temporaraily fix this error you need to set your application in plesk to use FastCGI instead of FPM served by Apache/Nginx.
I once had this issue and I solved by this, I created an .htaccess file in the target website I was trying to access.
<IfModule mod_headers.c>
SetEnvIf Origin "http(s)?://(www\.)?(mydomain)$" AccessControlAllowOrigin=$0$1
Header add Access-Control-Allow-Origin *
</IfModule>
Its an IF condition if the domain which is requesting has mydomain in it then it will allow you to access.
The CORS policy should also specify which headers you can send.
The 503 is a little bit strange. I think you need to set Content-Type in the list of allowed headers, and maybe others. According to MDN these: https://developer.mozilla.org/en-US/docs/Glossary/simple_header are the headers that you don't need to explicitly send
header('Access-Control-Allow-Headers: Content-Type, etc');

Jquery Ajax return nothing while trying to send an email [duplicate]

Mod note: This question is about why XMLHttpRequest/fetch/etc. on the browser are subject to the Same Access Policy restrictions (you get errors mentioning CORB or CORS) while Postman is not. This question is not about how to fix a "No 'Access-Control-Allow-Origin'..." error. It's about why they happen.
Please stop posting:
CORS configurations for every language/framework under the sun. Instead find your relevant language/framework's question.
3rd party services that allow a request to circumvent CORS
Command line options for turning off CORS for various browsers
I am trying to do authorization using JavaScript by connecting to the RESTful API built-in Flask. However, when I make the request, I get the following error:
XMLHttpRequest cannot load http://myApiUrl/login.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access.
I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?
This is the request code:
$.ajax({
type: 'POST',
dataType: 'text',
url: api,
username: 'user',
password: 'pass',
crossDomain: true,
xhrFields: {
withCredentials: true,
},
})
.done(function (data) {
console.log('done');
})
.fail(function (xhr, textStatus, errorThrown) {
alert(xhr.responseText);
alert(textStatus);
});
If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request.
When you are using Postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
WARNING: Using Access-Control-Allow-Origin: * can make your API/website vulnerable to cross-site request forgery (CSRF) attacks. Make certain you understand the risks before using this code.
It's very simple to solve if you are using PHP. Just add the following script in the beginning of your PHP page which handles the request:
<?php header('Access-Control-Allow-Origin: *'); ?>
If you are using Node-red you have to allow CORS in the node-red/settings.js file by un-commenting the following lines:
// The following property can be used to configure cross-origin resource sharing
// in the HTTP nodes.
// See https://github.com/troygoode/node-cors#configuration-options for
// details on its contents. The following is a basic permissive set of options:
httpNodeCors: {
origin: "*",
methods: "GET,PUT,POST,DELETE"
},
If you are using Flask same as the question; you have first to install flask-cors
pip install -U flask-cors
Then include the Flask cors package in your application.
from flask_cors import CORS
A simple application will look like:
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
#app.route("/")
def helloWorld():
return "Hello, cross-origin-world!"
For more details, you can check the Flask documentation.
Because
$.ajax({type: "POST" - calls OPTIONS
$.post( - calls POST
Both are different. Postman calls "POST" properly, but when we call it, it will be "OPTIONS".
For C# web services - Web API
Please add the following code in your web.config file under the <system.webServer> tag. This will work:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
Please make sure you are not doing any mistake in the Ajax call.
jQuery
$.ajax({
url: 'http://mysite.microsoft.sample.xyz.com/api/mycall',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
type: "POST", /* or type:"GET" or type:"PUT" */
dataType: "json",
data: {
},
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
});
Note: If you are looking for downloading content from a third-party website then this will not help you. You can try the following code, but not JavaScript.
System.Net.WebClient wc = new System.Net.WebClient();
string str = wc.DownloadString("http://mysite.microsoft.sample.xyz.com/api/mycall");
Deep
In the below investigation as API, I use http://example.com instead of http://myApiUrl/login from your question, because this first one working. I assume that your page is on http://my-site.local:8088.
NOTE: The API and your page have different domains!
The reason why you see different results is that Postman:
set header Host=example.com (your API)
NOT set header Origin
Postman actually not use your website url at all (you only type your API address into Postman) - he only send request to API, so he assume that website has same address as API (browser not assume this)
This is similar to browsers' way of sending requests when the site and API has the same domain (browsers also set the header item Referer=http://my-site.local:8088, however I don't see it in Postman). When Origin header is not set, usually servers allow such requests by default.
This is the standard way how Postman sends requests. But a browser sends requests differently when your site and API have different domains, and then CORS occurs and the browser automatically:
sets header Host=example.com (yours as API)
sets header Origin=http://my-site.local:8088 (your site)
(The header Referer has the same value as Origin). And now in Chrome's Console & Networks tab you will see:
When you have Host != Origin this is CORS, and when the server detects such a request, it usually blocks it by default.
Origin=null is set when you open HTML content from a local directory, and it sends a request. The same situation is when you send a request inside an <iframe>, like in the below snippet (but here the Host header is not set at all) - in general, everywhere the HTML specification says opaque origin, you can translate that to Origin=null. More information about this you can find here.
fetch('http://example.com/api', {method: 'POST'});
Look on chrome-console > network tab
If you do not use a simple CORS request, usually the browser automatically also sends an OPTIONS request before sending the main request - more information is here. The snippet below shows it:
fetch('http://example.com/api', {
method: 'POST',
headers: { 'Content-Type': 'application/json'}
});
Look in chrome-console -> network tab to 'api' request.
This is the OPTIONS request (the server does not allow sending a POST request)
You can change the configuration of your server to allow CORS requests.
Here is an example configuration which turns on CORS on nginx (nginx.conf file) - be very careful with setting always/"$http_origin" for nginx and "*" for Apache - this will unblock CORS from any domain (in production instead of stars use your concrete page adres which consume your api)
location ~ ^/index\.php(/|$) {
...
add_header 'Access-Control-Allow-Origin' "$http_origin" always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
if ($request_method = OPTIONS) {
add_header 'Access-Control-Allow-Origin' "$http_origin"; # DO NOT remove THIS LINES (doubled with outside 'if' above)
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Max-Age' 1728000; # cache preflight value for 20 days
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'My-First-Header,My-Second-Header,Authorization,Content-Type,Accept,Origin';
add_header 'Content-Length' 0;
add_header 'Content-Type' 'text/plain charset=UTF-8';
return 204;
}
}
Here is an example configuration which turns on CORS on Apache (.htaccess file)
# ------------------------------------------------------------------------------
# | Cross-domain Ajax requests |
# ------------------------------------------------------------------------------
# Enable cross-origin Ajax requests.
# http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity
# http://enable-cors.org/
# <IfModule mod_headers.c>
# Header set Access-Control-Allow-Origin "*"
# </IfModule>
# Header set Header set Access-Control-Allow-Origin "*"
# Header always set Access-Control-Allow-Credentials "true"
Access-Control-Allow-Origin "http://your-page.com:80"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Allow-Headers "My-First-Header,My-Second-Header,Authorization, content-type, csrf-token"
Applying a CORS restriction is a security feature defined by a server and implemented by a browser.
The browser looks at the CORS policy of the server and respects it.
However, the Postman tool does not bother about the CORS policy of the server.
That is why the CORS error appears in the browser, but not in Postman.
The error you get is due to the CORS standard, which sets some restrictions on how JavaScript can perform ajax requests.
The CORS standard is a client-side standard, implemented in the browser. So it is the browser which prevent the call from completing and generates the error message - not the server.
Postman does not implement the CORS restrictions, which is why you don't see the same error when making the same call from Postman.
Why doesn't Postman implement CORS? CORS defines the restrictions relative to the origin (URL domain) of the page which initiates the request. But in Postman the requests doesn't originate from a page with an URL so CORS does not apply.
Solution & Issue Origins
You are making a XMLHttpRequest to different domains, example:
Domain one: some-domain.com
Domain Two: some-different-domain.com
This difference in domain names triggers CORS (Cross-Origin Resource Sharing) policy called SOP (Same-Origin Policy) that enforces the use of same domains (hence Origin) in Ajax, XMLHttpRequest and other HTTP requests.
Why did it work when I made the request via the Chrome extension
Postman?
A client (most Browsers and Development Tools) has a choice to enforce the Same-Origin Policy.
Most browsers enforce the policy of Same-Origin Policy to prevent issues related to CSRF (Cross-Site Request Forgery) attack.
Postman as a development tool chooses not to enforce SOP while some browsers enforce, this is why you can send requests via Postman that you cannot send with XMLHttpRequest via JS using the browser.
For browser testing purposes:
Windows - Run:
chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security
The command above will disable chrome web security. So for example if you work on a local project and encounter CORS policy issue when trying to make a request, you can skip this type of error with the above command. Basically it will open a new chrome session.
You might also get this error if your gateway timeout is too short and the resource you are accessing takes longer to process than the timeout. This may be the case for complex database queries etc. Thus, the above error code can be disguishing this problem. Just check if the error code is 504 instead of 404 as in Kamil's answer or something else. If it is 504, then increasing the gateway timeout might fix the problem.
In my case the CORS error could be removed by disabling the same origin policy (CORS) in the Internet Explorer browser, see How to disable same origin policy Internet Explorer. After doing this, it was a pure 504 error in the log.
To resolve this issue, write this line of code in your doGet() or doPost() function whichever you are using in backend
response.setHeader("Access-Control-Allow-Origin", "*");
Instead of "*" you can type in the website or API URL endpoint which is accessing the website else it will be public.
Your IP address is not whitelisted, so you are getting this error.
Ask the backend staff to whitelist your IP address for the service you are accessing.
Access-Control-Allow-Headers
For me I got this issue for different reason, the remote domain was added to origins the deployed app works perfectly except one end point I got this issue:
Origin https://mai-frontend.vercel.app is not allowed by Access-Control-Allow-Origin. Status code: 500
and
Fetch API cannot load https://sciigo.herokuapp.com/recommendations/recommendationsByUser/8f1bb29e-8ce6-4df2-b138-ffe53650dbab due to access control checks.
I discovered that my Heroku database table does not contains all the columns of my local table after updating Heroku database table everything worked well.
It works for me by applying this middleware in globally:
<?php
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')
->header('Access-Control-Allow-Headers', "Accept,authorization,Authorization, Content-Type");
}
}

Woocommerce rest api invalid signature (error 401) on post request

I am working on an Ionic 2 project for a woocommerce store. I am using Woocommerce REST API in my app and for testing the API with OAuth-1.0 using Postman Chrome App. I am getting proper responses with GET requests but for POST requests, I am getting error of signature mismatch, as:
{
"code": "woocommerce_rest_authentication_error",
"message": "Invalid Signature - provided signature does not match.",
"data": {
"status": 401
}
}
I struggled with this for a few days (using angular) and finally figured out that it was a CORS issue. The browser actually sends an OPTIONS request, which the woocommerce-api receives as GET. Using this tool helped with troubleshooting.
Finally solved it by setting my .htaccess as follows;
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L,E=HTTP_ORIGIN:%{HTTP:ORIGIN}]]
Header set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Credentials "true"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
You can refer to this answer for a detailed explanation

Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers. (CORS )

I have a main domain and a subdomain (Mautic Is Installed), unfortunately, I have a cross-origin HTTP request problem if mautic is setup within a subdomain. When I load the example.com I get the following errors in Safari Console:
Failed to load resource: Origin https://example.com is not allowed by Access-Control-Allow-Origin. XMLHttpRequest cannot load https://subdomain.example.com/mtc.
Origin https://example.com is not allowed by Access-Control-Allow-Origin.
Which make sense for security reason.
So, I add header set Access-Control-Allow-Origin: https://example.com to https://subdomain.example.com /etc/httpd/conf/httpd.conf file. Thanks to this article about CORS on MDN. But, now I get the following error:
Failed to load resource: Credentials flag is true, but Access-Control-Allow-Credentials is not "true".
MLHttpRequest cannot load https://subdomain.example.com/mtc. Credentials flag is true, but Access-Control-Allow-Credentials is not "true".
Then, I add header set Access-Control-Allow-Credentials: true to /etc/httpd/conf/httpd.conf file. But I still get an error:
Failed to load resource: Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers.
XMLHttpRequest cannot load https://subdomain.example.com/mtc. Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers
And, this is where I'm stuck, Can someone help me? Thanks in advance.
I find the solution to this issue. What you need to do is set the Origin, Headers, and Credentials. I miss the "headers" section which I didn't specify in my httpd.conf. Here is the complete configuration:
Header set Access-Control-Allow-Origin: https://example.com
Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"
Header set Access-Control-Allow-Credentials true

Categories