Api Gateway cannot allow Access-Control-Allow-Origin - javascript

This url is in AWS API Gateway with method get and stage is well deployed.
And I enabled CORS following the aws document.
Here are my steps to enable CORS.
-Resource->action->enable CORS->
default setting ->enable CORS and replacing the CORS headers.
There is no error log in CORS result.
I am not a profesional web developer and my browser is safari.
Here is my code to query "http://my.com"
function request(idex) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", "http://my.com", true);
xmlHttp.send(null);}
The console print the error :
XMLHttpRequest cannot load "http://my.com" Origin http://example.com is not allowed by Access-Control-Allow-Origin.
If there are some mistakes in javascript request or in API Gateway deploy?

After consulting and trying each method, I found the error as following.
According to AWS document, we can not deploy our api before enabling CORS. All the settings about the header and CORS must be set before being deployed.
But the API Gateway does not block this setting nor does it show any error dialog. API Gateway will not change the header even if your setting process shows success.

The cross origin problem is from server side not javascript side. When the server does not allow request from other domains it throws cross origin error. But you said you already added CORS in aws instance
As the javascript is only accessing the service from my.com, You need to added proper domain mapping in your my.com site to tell that request will come from another domain called example.com. might be the server is not properly configured. or try if server is expecting any header.
try to see the result in any rest client like soapui, rect client plugin in chrome, etc. once you confirm that there is no problem in server, try it from javascript
To test there is a chrome plugin you can try
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

Related

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error while the header is given

I'm trying to get informations from a SystemLinkServlet.
So I tried to execute this JavaScript code from a Nintex Forms (Sharepoint) :
var http = new XMLHttpRequest();
var url = 'www.exampleservlet.com';
var params = "anyxml"
http.open('POST', url, true)
http.setRequestHeader('Content-type', 'application/xml');
http.setRequestHeader('Access-Control-Allow-Origin', '*');
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
};
http.send(params);
But I still got this error in my console :
Access to XMLHttpRequest at 'www.exampleservlet.com' from origin 'www.exampleorigin.com' 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.
It seems that the header is ignored or maybe I can't set multiple request headers?
It works on Postman.
Update
So It worked with an extension but apparently, I can't set headers with JavaScript code in my Nintex Forms.
I'm trying to find to pass those headers without using an extension.
If you are using PHP, try adding the following code at the beginning of the php file:
If you are using localhost, try this:
header("Access-Control-Allow-Origin: *");
If you are using external domains such as server, try this:
header("Access-Control-Allow-Origin: http://www.webiste.com");
Also you I suggest you to use this extension:
https://chrome.google.com/webstore/detail/cors-unblock/lfhmikememgdcahcdlaciloancbhjino?hl=en
Postman or other similar tools provide you development environments. In this way, you can ignore and pass CORS rule while sending request and getting response by changing tool settings. But if you sending request via browser(chrome, firefox etc.), browsers always add some preflight controls.
For example, browser send options message to get server side rule before your http request. So that invalid or wrong requests are blocked by browser before processing your http request.
In your case, server side must include your domain information. You can not change this communication rule from client side by adding just "Access-Control-Allow-Origin: *" or "Access-Control-Allow-Origin: http://www.webiste.com" statements.

Intune API - CORS not enabled when uploading file to azure via link from creating mobileAppContentFile

I called https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/<id>/<LOBType>/contentVersions/<content_version_id>/files, and received the azureStorageUri from it, but when I try to upload something into it (splitting the file into chunks), I always get 403 CORS not enabled.
I add $comp=block&blockid=<base64 block id> to the received uri.
My header is:
'x-ms-block-type': 'BlockBlob'
The exact error I receive is:
<Error>
<Code>CorsPreflightFailure</Code>
<Message>CORS not enabled or no matching rule found for this request.
RequestId:ce3ea3a7-f01e-0068-24b5-2c0795000000
Time:2018-08-05T12:10:00.6698414Z</Message>
<MessageDetails>No CORS rules matches this request</MessageDetails>
</Error>
Seeing as I always get the CORS issue, I tried enabling it by following this page, but, when making the request, again I receive the same CORS error.
I'm running it in my browser, if it's any help.
I'm kinda stuck and don't know how to proceed now. I'd be happy for any help. Thanks! :)
Edit: When I make the same request via Postman, it works just fine.
I'm kinda stuck and don't know how to proceed now
If you want to send a cross-origin request successfully, the request must match the CORS configuration including the request origin, headers & response headers. By default, CORS is disabled for each service. You could add the CORS setting for storage service. We could get more information about CORS from this article.
Note: CORS is not supported for Premium Storage accounts.
We could set it from Azure portal.
You can also use the wildcard character '*' to allow all origin domains to make requests via CORS.

Issue with reading Response headers

I am trying to build a chrome extension for which i need to ping to different machines.The code which i tried with is able to read the response headers for a https site but not for http.I am new to Javascripting. Any help would be great.I understand it is a CORS issue and tried setting the headers in the client code.many forums mention it setting al the server side but where can I do in this case? Please find the code below and the plugin UI and response returned from https site in the snapshot.
Code--
url="https://www.icicibank.com/";
//url = "www.rediff.com/";
ping = new XMLHttpRequest();
ping.open("get", url,true);
//ping.setRequestHeader("Access-Control-Allow-Origin","*");
// ping.setRequestHeader("Access-Control-Allow-Credentials", "true");
ping.send(null)
ping.onreadystatechange=function() {
if (ping.readyState==4) {
alert(ping.getAllResponseHeaders());
//alertify.alert(ping.getAllResponseHeaders());
}
}
Thanks
CORS is indeed part of the server response, not the request. So you cannot "set" it on your side.
However, extensions are allowed to bypass CORS restrictions and make cross-origin requests. But for that you need to list domains you're going to connect to in manifest permissions. The user will be warned, at install time, that you'll interact with those domains.
For example, to allow requests to http://example.com and https://example.com domains regardless of CORS, you need to include in the manifest:
"permissions" : [
"*://example.com/"
],
If you can't say which sites you'll need to connect to in advance, you'll either need permissions for all urls (special permission, literally, "<all_urls>") or use Optional Permissions to request that at runtime.

No 'Access-Control-Allow-Origin' header with Microsoft Online Auth

I am trying to make a simple request to get an access token using the Microsoft graph OAuth endpoint. When I send the simple request below I get
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:8080/myapprunninglocally' is therefore not allowed access.**"
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://login.microsoftonline.com/common/oauth2/authorize?client_id=<client_id>&scope=wl.signin%20wl.calendars_update&response_type=token&redirect_uri=localhost:8080/myapprunninglocally", true);
xhttp.send();
I have also registered this app using Microsoft Azure Directory, requested ALL permissions, and used the delegated client_id.
I have read up on CORS and I am aware Cross-Origin Policies however, I'm aware there are APIs which expose endpoints that include the 'Access-Control-Allow-Origin' in their response headers. Is anyone able to help?
Your not going to be able to run that from the client. Part of the CORS setup requires that microsoftonline.com adds your domain to their CORS supported whitelist.
I would suggest that you make a call a service on your server, which then makes the request server to server.
To integrate AAD in javascript, we suggest you to use azure-activedirectory-library-for-js which is a library in javascript for frontend to integrate AAD with a ease.
There are 2 options we need to pay attention on before we use ADAL for JS:
According the node at https://github.com/OfficeDev/O365-jQuery-CORS#step-6--run-the-sample:
Note This sample will not work in Internet Explorer. Please use a different browser, such as Google Chrome. ADAL.js uses an iframe to get CORS API tokens for resources other than the SPA's own backend. These iframe requests require access to the browser's cookies to authenticate with Azure Active Directory. Unfortunately, cookies are not accessible to Internet Explorer when the app is running in localhost.
Enable the oauth2AllowImplicitFlow of your Azure AD application. Refer to https://crmdynamicsblog.wordpress.com/2016/03/17/response-type-token-is-not-enabled-for-the-application-2/ for the detailed steps.
Here is the code sample to acquire access token from Microsoft Graph:
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.14/js/adal.min.js"></script>
<body>
login
access token
</body>
<script type="text/javascript">
var configOptions = {
tenant: "<tenant_id>", // Optional by default, it sends common
clientId: "<client_id>",
postLogoutRedirectUri: window.location.origin,
}
window.authContext = new AuthenticationContext(configOptions);
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
function getToken(){
authContext.acquireToken("https://graph.microsoft.com",function(error, token){
console.log(error);
console.log(token);
})
}
function login(){
authContext.login();
}
</script>

Simple CORS does not work (even though it should)

I'm trying to hack my back-end, which exposes a REST API. The worst thing that can happen to my database according to firefox CORS policy is that I can create a new object with POST request, as it does not need a preflight. This is the simple code (I'm running it via jsfiddle, but it shouldn't mean a thing)
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://127.0.0.1:8000/api/v1/company", true);
xhttp.withCredentials = true;
xhttp.setRequestHeader('Content-Type', 'text/plain');
xhttp.send('{description:"This company was added by pure hacking"}');
But I'm getting an error in the console:
Blocked loading mixed active content "http://127.0.0.1:8000/api/v1/company"
The error is not because of SOP, its a mixed content error, that is making an http request on a https page.
jsfiddle defaults to https but allows http, but only on saved fiddles.
Change the url of your fiddle to use http instead of https

Categories