Difference between CORS and HTTP requests to a 3rd party API - api

Are GET requests considered CORS since the request is obtaining resources from another domain?
I get from Wikipedia that CORS is:
"a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the resource originated."
However given this example:
$.ajax({
type: "GET",
url: "https://api.twitch.tv/kraken/base",
success: function(data){
//do stuff
}
});
If www.mywebsite.com (a domain) made the above GET request to Twitch (a domain outside the domain) does this count as CORS?

A HTTP request is a HTTP request.
Normally when you're on one domain, you are restricted to do stuff on another domain. This is called the browser sandbox.
CORS is a way for third party domains (twitch in your case) to grant you access after all.
In the particular example you state, twitch will indeed need to set the appropriate CORS headers to give you access. If twitch doesn't do this, you will not be able to read data.
Note that your code sample is horribly broken.

Related

How do I configure stand alone Blazor WebAssembly app to allow incoming cross origin redirect?

Objective is to integrate payment gateway to from Stand alone Blazor WebAssembly application. My payment page component has a form that submit directly to the payment gateway like this:
<form action="https://gateway.bank.com" method="POST">
Clicking submit button in the form redirects correctly. After the user complete payment transaction on the bank page, user is redirected back to my app along with response header. Although the redirected url is correct, browser throws 404. Reading more, I found out that since the request is originated from another domain, it gets blocked by CORS. Read many articles about configuring CORS policy for server, but how do I configure it on the client app to allow incoming requests?
Tried the following:
Added Nuget package Microsoft.AspNetCore.Cors
Inserted [DisableCors] attribute on the page
Added CORS policy on Main()
builder.Services.AddCors(options =>
{
options.AddPolicy("Open",
builder => builder.AllowAnyOrigin().AllowAnyHeader());
});
None of these worked though.
Just to ensure the approach is correct I have implemented solution using razor pages with [IgnoreAntiforgeryToken] on page model; it is successful. Help appreciated to find where am I going wrong with WebAssembly. Kindly note that I don't have a server project, only a stand alone WebAssembly project.
If the request is being blocked by CORS, there is nothing you can do on your website to avoid this. CORS is a security mechanism of browsers inspecting the response from a server. If the server does not add the proper CORS header to the response, the browser blocks the response from getting to the site loaded in the browser.
This is an intentional and good (if sometimes frustrating) part of the internet. You would need to contact the bank and request your website be added to the list of allowed origins. They would add your website's URL to the Allow-Access-Allow-Origin header. Because your URL is now part of the cool-kids list, the browser will allow the response to reach your site and will no longer throw a CORS error.

Why token-based authentication is better than cookie-based authentication in CORS/Cross-domain scenario?

I have seen in many places that one of the benefits of token-based authentication over cookie-based authentication is it is better suite for CORS/cross-domain scenario.
But why?
Here is a CORS scenario:
An HTML page served from http://domain-a.com makes an <img> src
request for http://domain-b.com/image.jpg.
Even if there's a token on my machine, how could the mere <img> tag know where to find and send it?
And according to here, it is suggested to store JWT as cookie, so how could that survive the CORS/cross-domain scenario?
ADD 1
Token-based authentication is easier to scale out than session-cookie one. See a related thread here: Stateless web application, an urban legend?
Just for clarification: Requests to any subdomain that you have are also considered as cross origin request (ex. you make request from www.example.com to api.example.com).
A simple <img> GET request to another origin is, indeed, cross origin request as well, but browsers are not using preflighted (OPTION) requests if you use GET, HEAD, POST requests only, and your Content-Type header is one of the followings:
application/x-www-form-urlencoded
multipart/form-data
text/plain
Therefore simple <img> request to another origin won't have problem (regardless if subdomain or totally another domain), as it won't go through preflight, unless it requires credentials, because when you add Authorization header, the request needs to go through preflight.
About storing in localstorage vs in cookie: Localstorage has single origin policy, meaning you cannot access the data you have stored from the subdomain, ie, example.com cannot access data in localstorage of api.example.com. On the other hand, using cookies, you can define which subdomains can access to the cookie. So you can access your token in stored in cookie and send it to server with your requests. Cookies also doesn't allow to access data across different domains.
Hope this helps.

Changing request and response with an Apache Proxy Server

I want to use an Apache proxy server (mod_proxy) to intercept all requests and responses to a web server. However I want to change requests and responses before redirecting them. Simply rewriting URLs is easy and documented, but the changes I want to make are more sophisticated, namely they need to inspect the request for user credentials as well as conditionally make redirects.
Is this possible in Apache's mod_rewrite, possibly in combination with other modules?
While the main goal is to implement this in Apache, I would also be happy with an alternative solution which doesn't necessarily use Apache.
Here is a more precise explanation of what I want to achieve, to give a little more context:
Check each incoming request for user credentials. If credentials are present, they are replaced by the user information which the web server can use to identify the user (Ideally in the Authorization header)
For example, let's assume a request contains a cookie which authenticates the request as beeing sent from the user "John", this cookie is removed, and the Authorization header is changed to Authorization Authenticated_by_proxy {"id":12345,"name":"John"}
Check each answer to see if it's an Error 403. If this is the case and the user is not logged in, redirect the user to a login page instead of forwarding the error

Can CSRF Be Circumvented By JSONP

I'm very new to CSRF protection so please excuse if I make poor assumptions or if I'm missing something, but I'd like to make sure I'm doing all I can to prevent CSRF. From my research so far, I've found the following:
CSRF can be thwarted (and is probably best thwarted) by placing a nonce parameter within the request body of all HTML POSTs, only using POSTs to modify data, and on the server side verify the token is valid before processing the request.
A malicious website can send requests to my site (thwarted by the nonce), but they can't read responses because of same-origin policies in place on browsers. Assuming that someone is using a secure browser, a malicious site cannot GET a page from my site using AJAX, read the nonce, and use it for themselves.
Script tags are not bound by same-origin policies in most (possibly any) browsers and can therefore allow for content to be read from other sites.
When I got to point 3 I decided to try to get at HTML content in Chrome using JSONP; I opened up my console (with a page not from localhost) and ran the following code:
$.ajax({
url: "http://localhost:8080/my-app/",
dataType: "jsonp",
jsonp: "alert"
}).done(function(data) {
alert(data);
});
What I received in the console window was the this:
Resource interpreted as Script but transferred with MIME type
text/html
As far as I can tell the browser is essentially telling me that it received the content, proceeded to parse the response, but stopped because the type was not application/json. So finally, my question is, can this be compromised? Even though the browser failed to parse the response as JSON, it does have the response. Is there a way that this response could be parsed as HTML, grab my CSRF nonce, and compromise the protections I'm trying to enforce? It would seem to me (and I hope this to be true) that browsers will not allow this, just like they don't allow cross domain requests in the first place for basically all other communication, and that's what we as developers are relying upon (in addition to same-origin policies) to protect our sites. Is my thinking correct?

How do REST APIs work with JavaScript when the same-origin policy exists for browsers?

I am working with Flickr's REST API and it's working fine. By that, I mean I'm making an AJAX call to the Flickr API and getting a JSON object back, parsing the object, etc. etc.
But this raises a question in my mind. If browsers follow the same-origin policy, then how can they make these types of API requests?
This DEMO fiddle is working, but it sends a cross-domain request to the Flickr domain.
How does this cross-domain request work?
The cross-domain request:
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=" +
id + "&lang=en-us&format=json&jsoncallback=1");
What you need to understand is that, while browsers do enforce the same origin policy (SOP), there are exceptions when SOP is not enforced. For example, if you have an HTML page - you can insert <img> tags that point to images on any domain. Therefore, the SOP doesn't apply here and you are making a cross-origin HTTP GET request for an image.
The demo you linked to works since it uses a mechanism that works in a similar way. The mechanism is called JSONP - http://en.wikipedia.org/wiki/JSONP and I suggest you read the wiki entry and some other blog posts. In essence, JSONP dynamically injects <script> tags to send a request to any domain (the parameters of the request are added as URL query params), since the same origin policy does not apply to <script> tags (as it doesn't apply to <img> tags).
Another way to invoke REST APIs on other domains is to use the cross-origin resource sharing mechanism (CORS) - http://en.wikipedia.org/wiki/Cross-origin_resource_sharing. In essence, this mechanism enables that browsers don't deny cross-origin request, but rather ask the target service if it wants to allow a specific cross-origin request. The target service tells the browser that it wants to allow cross-origin requests by inserting special HTTP headers in responses:
Access-Control-Allow-Origin: http://www.example.com