unable to access the prestashop webservice via getJSON - web-services

I am trying to use the webservice prestashop (1.6) to get my product by using the jquery function getJSON() but on the console's browser, I get the following error :
XMLHttpRequest cannot load
http://www.pourquoilavie.org/api/products/?ws_key=XXXXXkeyXXXXXXXXX&io_format=JSON.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost' is therefore not allowed access.
I tried to add " Header set Access-Control-Allow-Origin: * " to the htaccess but without success.
I wonder if there is another way to set a header (except using php with header('Access-Control-Allow-Origin: *'); )

I solved the issue by myself, I just add header('Access-Control-Allow-Origin: *'); on the file dispatcher.php in the webservice folder

In prestashop 1.6 you can try to add this in
./prestafolder/webservice/dispatcher.php
for security reason, instead of asterisk you can type domain name
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Origin: http://example.com');
FYI
If you will still have problems or Unauthorized message, try to change your url from
http://KEYTOKEN#example.com/api/
into
http://example.com/api/?ws_key=KEYTOKEN

If you are working with Angular or Similar Frameworks, modify and add the following code according to your environment on the first line of prestashop_folder/webservice/dispatcher.php file
// Allow from any origin
if(isset($_SERVER["HTTP_ORIGIN"]))
{
// You can decide if the origin in $_SERVER['HTTP_ORIGIN'] is something you want to allow, or as we do here, just allow all
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
}
else
{
//No HTTP_ORIGIN set, so we allow any. You can disallow if needed here
header("Access-Control-Allow-Origin: *");
}
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 600"); // cache for 10 minutes
if($_SERVER["REQUEST_METHOD"] == "OPTIONS")
{
if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_METHOD"]))
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT"); //Make sure you remove those you do not want to support
if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"]))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
//Just exit with 200 OK with the above headers for OPTIONS method
exit(0);
}

for me i tried with react app i had to made some modification in dispatcher.php and add for option preflight 200 return
i added in the dispatcher.php header
//to access from external browser
header('Access-Control-Allow-Origin: *');
header( 'Access-Control-Allow-Headers: Authorization, Access-Control-Allow-Headers,
Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-
Control-Request-Headers,Output-Format');
header( 'Access-Control-Allow-Methods: GET, OPTIONS, HEAD, PUT, DELETE');
header( 'Access-Control-Allow-Credentials: true');
then modified like this after in the code
if ($method === 'OPTIONS') {
die('200');
ob_end_flush();
}else{
if (isset($_SERVER['PHP_AUTH_USER'])) {
....
}

Related

How can I embed in my site a CAPTCHA from another site, resolve it MANUALLY, send back to the original site and get the TOKEN?

The intention is not to resolve CAPTCHA automatically. Every user of my site will have to resolve the CAPTCHA.
The intention is to use free data from another site. These data are public and free, but to avoid massive requests, they are protected with CAPTCHA.
This is what I've done but doesn't work:
Create a proxy.php that manage and forward the requests to the original site.
Copy all headers from the original request (request of the CAPTCHA) and add them to the proxy. So, this is the form to resolve the CAPTCHA:
xxx is my site, example.com is the site that I want to resolve captcha and get data:
<img id="imgCaptcha" src="https://xxx/proxy.php?curl=https://example.com/Captcha&type=image&lang=it" style="width:200px;">
<input type="text" id="captcha">
<button type="button" id="btn_resolve">Resolve</button>
On button click, send the input text and check if it is resolved:
xxx is my site, example.com is the site that I want to resolve captcha and get data:
$('#btn_resolve').on('click',function(e) {
e.preventDefault();
var captcha = $('#captcha').val();
$.get('https://xxx/proxy.php?https://example.com/Captcha&type=check&captcha='+captcha, function(data, status) {
alert(JSON.stringify(data));
});
});
The result is always {"result":false,"token":"","message":null}
I think that the problem is with JSESSIONID cookie that I set in the proxy.php, but seems filtered out from Chrome with this motivation: "This cookie was blocked because its path was not an exact match for or a superdirectory of the request url's path".
Honestly I've got not clear if I can do this and how to do this: it seems that last versions of Chrome blocked some coockies. How can I do this with PHP CURL bypassing Chrome filters?
I resolved it adding all needed cookies in proxy.php file.
Proxy.php forward the request using curl.
This is a good starting point for a cross domain proxy in PHP that uses CURL commands
PHP CORS Proxy by softius
Then you can read JSESSIONID from after requesting the CAPTCHA image, and forward it to the proxy and add it and the others to the request:
header('Set-Cookie: cross-site-cookie=name; SameSite=None; Secure');
header('Set-Cookie: XSRF-TOKEN=XXXXX');
if (isset($_REQUEST['jsessionid'])) {
setcookie("JSESSIONID", NULL, 0, "/");
header('Set-Cookie: JSESSIONID='.$_REQUEST['jsessionid']);
}

XMLHttpRequest error while using http post flutter web

I am facing this error XMLHttpRequest error. while making an HTTP post call to my API-AWS API Gateway. My current Flow is Flutter web -> API gateway -> lambda -> rds.
I know there are already a couple of question-related to this like but as suggested in one of the answers to add some headers in response to lambda. but it doesn't work for me.
After doing some research I found out that the problem is regarding to CORS. now disabling cors in chrome is a temporary fix and suggested in this question.
some other solution that I found after researching suggested to enabled cors in my API and also in the frontend part I have added headers but none of them works.
fetchData() async {
String url =
"myUrl";
Map<String, String> headers = {
"Access-Control-Allow-Origin": "*", // Required for CORS support to work
};
String json = '{"emailId":"emailId"}';
http.Response response =
await http.post(Uri.parse(url), headers: headers, body: json);
print(response.body);
return response.body;
}
what is the correct way of solving this problem?
1- Go to flutter\bin\cache and remove a file named: flutter_tools.stamp
2- Go to flutter\packages\flutter_tools\lib\src\web and open the file chrome.dart.
3- Find '--disable-extensions'
4- Add '--disable-web-security'
I have Solved my problem, and not going to delete this question because there aren't many well-defined solutions to this problem.
For Future viewer who is using flutter web and AWS API-gateway.
if you encounter this problem it means its from backend side not from flutter side
XMLHttpRequest error. is caused due to CORS
The solution to the problem you have to enable CORS in api-gateway follow this link.
but if you are using proxy integration with lambda and api-gateway then in that case enabling CORS doesn't going to help, you have to pass on headers from the response of lambda function. like
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*", // Required for CORS support to work
"Access-Control-Allow-Credentials": true, // Required for cookies, authorization headers with HTTPS
"Access-Control-Allow-Headers": "Origin,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,locale",
"Access-Control-Allow-Methods": "POST, OPTIONS"
},
body: JSON.stringify(item)
};
the format needs to be the same. also, one particular question that helps me a lot to understand this whole issue is going through the various answer of the question link.
Now comes my problem, what I'm doing wrong i that i am passing "Access-Control-Allow-Origin": "*", from frontend and enabling CORS in API gateway also send similar headers which are creating a problem for me
Access to XMLHttpRequest at 'API-URL' from origin 'http://localhost:63773' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. //this particular line
So after changing my function to this everything works perfectly fine
fetchData() async {
String url =
"API-url";
Map<String, String> headers = {
"Content-Type": "text/plain",
};
String json = '{"emailId":"emailId"}';
Map<String, String> map = Map();
map["emailId"] = "fake#gmail.com";
http.Response response = await http
.post(Uri.parse(url), headers: headers, body: jsonEncode(map))
.then((value) {
print("onThen> " + value.body.toString());
}).onError((error, stackTrace) {
print("onError> " +
error.toString() +
" stackTrace> " +
stackTrace.toString());
});
}
In flutter web api Access-Control-Allow-Origin use in header to might resolve this issue.
header("Access-Control-Allow-Origin: header");
in your backend php file add this code
<?php
header("Access-Control-Allow-Origin: *");
finish!

Cookie not added into request header

Like to ask a CORS cookie question again, I have spent quite some time on this but cannot resolve it.
Here is the situation.
I got a Backend api in nodejs(http://localhost:5000), and a React Frontend app(http://localhost:3000).
In Backend side, Cors setting is like this.
private initializeCors(){
this.app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Headers", "Content-Type, Accept");
res.header("Access-Control-Allow-Credentials", "true");
next();
});
}
I have set { credentials: "include" } in Fetch Api when login with username/password.
Set-Cookie has been set in response and I can see it saved in browser.
Cookie is with the format "Authorize=TOKEN;HttpOnly;Max-Age=3600;"
Cookie in browser
Then when route to another url and it cannot retrieve data from Backend with 401 exception.
Here is the code of the sequence call.
const credentialsInclude : "include" | "omit" | "same-origin" | undefined = "include";
function getAllPayments() {
const requestOptions = {
method: 'GET',
credentials: credentialsInclude
};
return fetch(apiUrls.GET_ALL_PAYMENTS, requestOptions).then(handleResponse);
}
I can see the cookie not added into header.
No cookie in header
I have followed the best answer of here, but cannot get it work.
Any suggestions? Thanks.
I have just figured out. The issue was not caused by the CORS settings. It caused by the Cookie itself.
For my case, I need to add Path=/; into Set-Cookie in response headers. So that the cookie from response could be added to sequenced requests after successful login.

Dart BrowserClient POST not including my cookies

I'm doing a BrowserClient POST across domains and don't see my cookies being included.
This the response I'm getting:
When I send another POST request, I don't see the cookies being included:
Going straight to the test page, I can see the cookies being included:
The Dart code I use to make a POST:
var client = new BrowserClient();
client.post(url, body: request, headers:{"Content-Type" : "application/json", "Access-Control-Allow-Credentials":"true"}).then((res) {
if (res.statusCode == 200) {
var response = JSON.decode(res.body);
callback(response);
} else {
print(res.body);
print(res.reasonPhrase);
}
}).whenComplete(() {
client.close();
});
Not sure about the Access-Control-Allow-Credentials header I'm including, with or without it, nothing changes.
Am I missing headers on the server side that needs to be set on the response or is Dartium blocking cross-domain cookies?
More details on Information Security and the reasoning behind setting cookies via the server.
Update: Enhancement request logged: https://code.google.com/p/dart/issues/detail?id=23088
Update: Enhancement implemented, one should now be able to do var client = new BrowserClient()..withCredentials=true; based on
https://github.com/dart-lang/http/commit/9d76e5e3c08e526b12d545517860c092e089a313
For cookies being sent to CORS requests, you need to set withCredentials = true. The browser client in the http package doesn't support this argument. You can use the HttpRequest from dart:html instead.
See How to use dart-protobuf for an example.

Varnish remove specific cookies from backend response

I need to remove specific cookies from the backend response in varnish.
My backend server sets a bunch of cookies that I don't need and unfortunately I can not control, so I want to delete them.
However I need some of the cookies, so I want to be able to remove cookies by their name.
For example I want to rename a cookie named bad_cookie, but at the same time keep a cookie named good_cookie.
I have found a lot of resources about removing specific request cookies, but none about removing backend response cookies.
Is this possible in Varnish?
If you want to rename I think it would be something like:
sub vcl_fetch {
#renamed after receiving the backend
set beresp.http.set-cookie = regsuball(beresp.http.set-cookie, "bad_cookie", "good_cookie");
set beresp.http.cookie = regsuball(beresp.http.cookie, "bad_cookie", "good_cookie"); }
}
sub vcl_deliver {
#renamed before sending the client
set resp.http.set-cookie = regsuball(beresp.http.set-cookie, "bad_cookie", "good_cookie");
set resp.http.cookie = regsuball(beresp.http.cookie, "bad_cookie", "good_cookie"); }
}
If you want to delete all cookies:
sub vcl_fetch {
#deleted after receiving the backend
remove beresp.http.set-cookie;
remove beresp.http.cookie;
}
sub vcl_deliver {
#deleted before sending the client
remove resp.http.set-cookie;
remove resp.http.cookie;
}
beresp.http.set-cookie reads only the first Set-Cookie header, If you want to delete some and keep others can use: github.com/varnish/libvmod-header**