No Access-Control-Allow-Origin using OneSignal setup - javascript

I am using OneSignal for web push messaging for a client website. I've followed the HTTPS setup. I went over it few times ensuring that everything was done right.
all the files were uploaded to the root of the domain
I've setup the manifest and put the needed initialize code in the header of the page
When I load the page I get:
Fetch API cannot load https://onesignal.com/api/v1players.
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 404. If an opaque response serves your needs,
set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I contacted the team directly, but they just copy pasted part of the documentation. No further assistance was given.
Using Chrome version 58 / Windows 10
What am I doing wrong?

https://onesignal.com/api/v1players responses apparently don’t include the Access-Control-Allow-Origin response header, and because they do not, your browser blocks your frontend JavaScript code from accessing the responses.
There are no changes you can make to your own frontend JavaScript code nor backend config settings that’ll allow your frontend JavaScript code to make requests the way you’re trying directly to https://onesignal.com/api/v1players and get responses back successfully.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS explains in more detail but the gist of it is that for CORS, the server the request is being sent to must be configured to send the Access-Control-Allow-Origin response header.
Anyway https://documentation.onesignal.com/docs/web-push-sdk-setup-https has official docs that explain their supported SDK, which apparently requires you to do something more like this:
<head>
<link rel="manifest" href="/manifest.json">
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async></script>
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(["init", {
appId: "YOUR_APP_ID",
autoRegister: false,
notifyButton: {
enable: true /* Set to false to hide */
}
}]);
</script>
</head>

The accepted answer is ok, you can solve most of the requirements by using tags:
OneSignal.push(function() {
/* These examples are all valid */
OneSignal.sendTag("key", "value");
OneSignal.sendTag("key", "value", function(tagsSent) {
// Callback called when tags have finished sending
});
OneSignal.sendTag("key", "value").then(function(tagsSent) {
// Callback called when tags have finished sending
});
});
But in case you want to edit the device information, there is no way (as of today) to edit the device metadata with the WebPush SDK. I needed to update the location periodically, and I didn't want to use tags. So, I sent the PUT request to https://onesignal.com/api/v1players like this:
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") { //ie8 ie9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
};
//then every time I needed to update the device
var url = 'https://onesignal.com/api/v1/players/' + playerId;
var xhr = createCORSRequest('PUT', url);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onload = function() {}; //success
xhr.onerror = function() {}; //error
var deviceInfo = {
"app_id": oneSignalAppId,
"timezone": (currentDateTime.getTimezoneOffset()) * -60, //offset from utc
//whatever fields you need to update
};
xhr.send(JSON.stringify(deviceInfo));

Related

Tumblr API OAuth with local test server

I'm trying to get posts from my tumblr blog and put them on a separate website page. To do this I registered an app on their OAuth page, but I'm having some issues when I try to actually request the authorization. My console spits out this message—
XMLHttpRequest cannot load https://api.tumblr.com/v2/blog/myblog.tumblr.com/posts?api_key=(MY_KEY).
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://127.0.0.1:63342' is therefore not allowed access.
(I've omitted the key value here for obvious reasons).
Now, my site isn't actually live yet, and I have a test server running at localhost:63342 but on their OAuth app settings page I have these options that I must fill out—
Is there a way to get this to work with my local test server? Here's the code that I'm calling to request access.
var request = new XMLHttpRequest();
request.open('GET', 'https://api.tumblr.com/v2/blog/myblog.tumblr.com/posts?api_key=(API_KEY)', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
console.log(data);
} else {
// We reached our target server, but it returned an error
console.log('server error');
}
};
request.onerror = function() {
// There was a connection error of some sort
console.log("ERROR!!!");
};
request.send();
Any help would be appreciated! Thanks!
Turn out my issue was using JSON instead of JSONP, which bypasses the Access-Control-Allow-Origin issue. I downloaded this JSONP library for Javascript ( I am not using JQuery in my project ) and was able to access the api by writing this:
JSONP('https://api.tumblr.com/v2/blog/myblog.tumblr.com/posts?api_key=(API_KEY)'
, function(data) {
console.log(data);
});
Which returns a JSON Object which I can then data from using something like data.response or whatever objects are in the array.
Again, my issue was not Tumblr not authorizing my test server. I was able to get this to work using 127.0.0.1:port as my application website & callback url.

Ajax request: Refused to set unsafe header

I am trying to play an audio using Google Text-To-Speech. Therefore I need to post a request to their endpoint with the Referer and the User-Agent properly set. This call should return an MP3 that I can play.
However, I get Refused to set unsafe header errors. This is my code. How can I do this?
$.ajax({
url: 'http://translate.google.com/translate_tts?ie=UTF-8&q=Hello&tl=en&client=t',
beforeSend: function(xhr) {
xhr.setRequestHeader("Referer", "http://translate.google.com/");
xhr.setRequestHeader("User-Agent", "stagefright/1.2 (Linux;Android 5.0)");
}, success: function(data){
el.mp3 = new Audio(data);
el.mp3.play();
}
});
You can't. It is impossible.
The specification requires that the browser abort the setRequestHeader method if you try to set the Referer header (it used to be that User-Agent was also forbidden but that has changed)..
If you need to set Referer manually then you'll need to make the request from your server and not your visitor's browser.
(That said, if you need to be deceptive about the user agent or referer then you are probably trying to use the service in a fashion that the owner of it does not want, so you should respect that and stop trying).
Note that while jQuery wraps XHR, the same rules apply to fetch.
Empty Origin and Referer headers with GET XMLHttpRequest from <iframe>
Well actually, it is possible; at least for ordinary web pages.
The trick consists in injecting an XMLHttpRequest
function into an empty <iframe>.
The origin of an empty <iframe> happens to be about://blank, which results in empty Origin and Referer HTTP headers.
HTML:
<iframe id="iframe"></iframe>
JavaScript:
const iframe = document.getElementById('iframe');
const iframeWin = iframe.contentWindow || iframe;
const iframeDoc = iframe.contentDocument || iframeWin.document;
let script = iframeDoc.createElement('SCRIPT');
script.append(`function sendWithoutOrigin(url) {
var request = new XMLHttpRequest();
request.open('GET', url);
request.onreadystatechange = function() {
if(request.readyState === XMLHttpRequest.DONE) {
if(request.status === 200) {
console.log('GET succeeded.');
}
else {
console.warn('GET failed.');
}
}
}
request.send();
}`);
iframeDoc.documentElement.appendChild(script);
JavaScript evocation:
var url = 'https://api.serivce.net/';
url += '?api_key=' + api_write_key;
url += '&field1=' + value;
iframeWin.sendWithoutOrigin(url);
Having the possibility of sending empty Origin and Referer HTTP headers is important to safeguard privacy when using third-party API services. There are instances where the originating domain name may reveal sensitive personal information; like being suggestive of a certain medical condition for example. Think in terms of https://hypochondriasis-support.org :-D
The code was tested by inspecting the requests in a .har file, saved from the Network tab in the F12 Developer View in Vivaldi.
No attempt in setting the User-Agent header was made. Please, comment if this also works.
There are some header, which browser doesn't allow programmer to set its value in any of the javascript framework (like jQuery, Angular, etc.) or XMLHttpRequest ; while making AJAX request. These are called the forbidden headers: Forbidden Header

XMLHttpRequest, send and security restrictions

I thought I could catch an error in send like this
try {
xhr.send();
} catch(e) {
// fix-me: With the
// bookmarklet on a https page
// you can't even send a HEAD
// request due to security
// restrictions. Check for
// this case here.
console.log("xhr.send, e=", e, method, window.location.href, url)
debugger;
}
console.log("I am here now");
However I never get to that console.log statement in the catch block after xhr.send.
In the console I instead get a message like this.
Mixed Content: The page at 'about:blank' was loaded over HTTPS,
but requested an insecure XMLHttpRequest endpoint 'http://m.org/'.
This request has been blocked; the content must be served over HTTPS.
I am here now.
Is it supposed to work this way? (I am using Google Chrome.)
Is there any way to find out that there was an error? (Except looking in the console. ;-) )
UPDATE
#giuscri added the very good question if I did consider that this is async. I actually missed that it could be, but it is not. A bit surprisingly. ;-)
Please see the this example. It contains this code:
var url = "http://nowhere.org/";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
console.log("onreadystatechance, readyState=", xhr.readyState);
};
xhr.onprogress = function(event) {
console.log("onprogress, readyState=", xhr.readyState);
console.log("onprogress, event=", event);
};
xhr.onerror = function(event) {
console.log("onerror, readyState=", xhr.readyState);
console.log("onerror, event=", event);
};
var method = "HEAD";
xhr.open(method, url, true);
try {
xhr.send();
} catch(e) {
console.log("xhr.send, e=", e, method, window.location.href, url);
}
console.log("After send");
When you run this page from https:// (as in the link above) the onerror function is not run. If you run the same example from file:// then onerror is run.
Connecting from HTTPS to HTTP URIs drops the security given by the underlying encryption. Web browsers blocks such requests until explicitly allowed by the user in order to prevent data leakage over plaintext connections. Further, there is also a change in origin (scheme, domain, port).
I allowed Mixed Content for the page you linked and I got the error about the different origin in console. Looks like the code works.
By the way, support for synchronous requests using XMLHttpRequest is deprecated, because it blocks user interaction until the request completes.

Javascript CORS JSON/JSONP Request

I have browsed most CORS and JSON request topics, and cannot understand why this first script works, but not the second. I would love to be educated in the ways of CORS and Javascript and XMLHTTPRequest2 and AJAX.
This works:
function wfs() {
var url = 'http://routes.cloudmade.com/8ee2a50541944fb9bcedded5165f09d9/api/0.3/51.22545,4.40730,%5B51.22,4.41,51.2,4.41%5D,51.23,4.42/car.js?lang=de&units=miles&callback=getRoute';
var script = document.createElement('script');
script.type="text/javascript";
script.src=url;
document.getElementsByTagName('head')[0].appendChild(script);
}
function getRoute(response) {
console.log(response);
}
This does not work:
function wfs() {
var url = 'http://routes.cloudmade.com/8ee2a50541944fb9bcedded5165f09d9/api/0.3/51.22545,4.40730,%5B51.22,4.41,51.2,4.41%5D,51.23,4.42/car.js?lang=de&units=miles';
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function(e) {
if (this.status == 200) {
var json = this.response;
console.log(json);
}
};
xhr.send();
}
Firebug shows a Red 200 Null Response.
However, the second script does work when I use a different url:
var url = 'http://ip.jsontest.com/?mime=2';
The first domain, http://routes.cloudmade.com/8ee2a50541944fb9bcedded5165f09d9/api/0.3/51.22545,4.40730,%5B51.22,4.41,51.2,4.41%5D,51.23,4.42/car.js?lang=de&units=miles, does not implement CORS (i.e. does not send a usable Access-Control-Allow-Origin header). http://ip.jsontest.com/?mime=2 does. There is nothing you can do about this -- it depends on the server.
The first block of code uses JSONP. What this actually does is inject a script tag into the document. Script tags can have external sources (if they are not of the same scheme, they may be blocked for security reasons). This allows the server to essentially send you javascript code that you insert into a <script> that gets run immediately.

Access HTTPS wcf service in HTML,Javascript, service and Web page hosted on different domains - CORS

I am trying to access WCF service hosted on server. The service is using SSL connection.
I assigned a self signed certificate in IIS.
The service is a restfull service.
I tried with two different scenarios:
1st scenario :
I hosted the web site to same server(client application which access service)
In this case the service is accessible and able to get response from service.
2nd scenario :
I hosted the web site to localhost,local machine.
From here when I am trying to make request to service method which is hosted on different web server it is not accessible.
Showing error "Method not allowed"
Here is code :
function testHttps()
{
jsonText3=JSON.stringify({"Name":"Avinash"});
url="https://ServerIP/WcfSecureService/Service.svc/GetName";
var xhr = createCORSRequest('POST', url);
if (!xhr) {
alert('CORS not supported');
}
xhr.onload = function() {
alert(xhr.responseText);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.setRequestHeader('Content-Type', 'application/json') ;
xhr.send(jsonText3);
}
function createCORSRequest(method, url)
{
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr)
{
xhr.open(method, url, true);
}
else if (typeof XDomainRequest != "undefined")
{
xhr = new XDomainRequest();
xhr.open(method, url);
} else
{
xhr = null;
}
return xhr;
}
How to make CORS call success with HTTPS?
I do not want to install any certificate on client site.
How to authenticate service from Javascript?
Please suggest...
Thanks for your help in advance.
--Avinash
Check this and this out.
I think your problem is not about https: is the server responding with an header like the following?
Access-Control-Allow-Origin: *
In case it's not, it's probably filtering out your local referer.
Furthermore, if you're using credentials the server can't use the "*" wildcard and has to specify every allowed domains, which don't include localhost, I guess.

Categories

Resources