No CORS needed for mobile apps? - android

When I make web applications, I usually have to add these headers to Express to allow CORS requests.
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
next();
});
But with React Native mobile apps, I don't have to do that. Why is that so?

The point of CORS is to prevent web pages loaded at one domain making AJAX requests or HTTP requests that modify data to other domains. The way it works is web browsers are built to send pre-flight HTTP OPTIONs requests before any such cross-site requests, & the server will send back a message with the Access-Control-* headers designating its CORS policy, & the browser will proceed or abort the request based on what it's told it can do. Since a native app is not a web page loaded from any domain at all, CORS restrictions are not needed or applied, the app's HTTP functions never send an OPTIONS pre-flight, & the server serves the request without CORS ever entering into it. The same is true if you were to try these requests in Postman. Note, however, that if you were to use a hybrid mobile app (Cordova/Ionic/Phonegap, etc.), you would have to deal with CORS, since these apps run in the device's WebView, which is a type of browser & will send pre-flight OPTIONS requests.
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Related

Access to XMLHttpRequest at "xxx" from origin 'null' has been blocked by CORS policy in Leaflet Android [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");
}
}

Android: How inspect http(s) request headers?

I'm developing an Android application, it is like a browser, has a web-view and sends http(s) requests. For debugging purpose, I want to be able to see the requests sent and received by the application (in particular the headers), but I'm unable to do so.
What i tried
I mainly debug the app with Chrome on PC, and use the Network Inspector in Chrome. The problem is that my app uses the ShouldInterceptRequest to intercept the requests an then manually sends a request with cronet. Chrome, in this case, shows some "provisional headers" that are from the original request, an not the headers of the actual request i sent manually.
I tried to use Fiddler and HTTP Toolkit, but the server I'm communicating with, doesn't like the certificate they use, so they can monitor correctly, but, if active, i cannot reach the page i need to monitor.
I also tried the Android Studio network inspector, but seems it work only for HttpURLConnection and Okhttp(1)
Thanks for your time.
If you're using a WebView, set a custom WebViewClient and override shouldInterceptRequest. That will pass in a WebResourceRequest object that will include all headers.

Handling Mobile app backend API domain change - iOS & Android

We have a mobile app that calls endpoints on host https://www.currentdomain.com. we are migrating to https://www.newdomain.com in a month
The network team is planning to setup a dns redirect from currentdomain to newdomain.
What is the best possible way to handle this change in the app with minimal change and work? What will happen if the app calls the endpoint on currentdomain after setting up the dns redirect?
You can support redirection in your APIs.I am not sure how much is it possible at your end but if yes, then no changes will be required at app side.
Otherwise http redirection can be handled easily by apps, like in iOS 1 method needs to be added & can redirect request to the desired url.
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/RequestChanges.html
Redirect handler in android
https://developer.android.com/reference/org/apache/http/client/RedirectHandler.html

Cordova app, file:// origin and CORS

I'm currently working on a Cordova app written with AngularJS.
When I run the built APK on the android tablet or the iPad, the requests are sent with the "Origin" header set to "file://". This makes the server to reject the request for CORS reasons.
I've seen that the origin should be set to "null", not "file://" when Cordova sends the requests.
I'm actually using cordova-plugin-whitelist.
The communication between the app and the server is using SOAP protocol, and i'm using an external module in the frontend that sends the requests with XmlHttpRequest.
I don't wan't, for security reasons, to allow "file://" origin on server side. Is there any way to remove the origin from the requests ? I tried to manually set the Origin header of the XmlHttpRequest, but of course, it creates an error "Refused to set unsafe header "Origin"".
How could I make this work without impacting the security ?
Does something like a Cordova plugin that removes the "Origin" header from all the AJAX exists ?
Thanks

How do I set a cookie to be used on all calls to the Worklight Server from a Native Android App

I'm building an native Android app with Worklight 6.0.0.1 and having trouble connecting to our production Worklight Server.
The server is fronted by a DataPower appliance that handles authentication and requires us to send a particular cookie on any call to the Worklight Server.
We tried using addGlobalHeader("Cookie", "cookie-name=cookievalue") to set this cookie, but found that using this API does not play nicely with the cookies that Worklight itself uses to manage it's session.
The cookie header is properly set for the initial request to Worklight, and Worklight responds with a challenge and sets JSESSIONID and WL_PERSISTENT_COOKIE.
Then, when the Android API answers this challenge we see 2 cookie headers being sent in the follow-up request which violates norms for http headers.
Cookie: JSESSIONID=<...>;WL_PERSISTENT_COOKIE=<...>
Cookie:
Oddly, if I go through a TCPMon proxy to inspect the traffic, I can connect successfully, but if I go directly against the DataPower address, it doesn't see the header and fails to reach Worklight.
What is the correct way to inject a cookie so my cookie goes into a single cookie header along with all of the other cookies that Worklight wants?
Add global header will add headers, it was not designed for cookies. If you need to set cookies I'd suggest trying Android's CookieStore. Create you cookie with all the relevant params (value/url/expiry etc) and add it to CookieStore
http://developer.android.com/reference/org/apache/http/client/CookieStore.html

Categories

Resources