Getting the request origin in a Django request - javascript

So I'm trying to enable cross origin resource sharing in Django, so I can post to an external site, and it's easy to do when I set
response["Access-Control-Allow-Origin"]="*"
but I want to instead have it check whether the origin is in an allowed list of origins (essentially to restrict it to only allow specific sites) but I can't seem to find anywhere in the Django request where I can get the origin information.
I tried using request.META['HTTP_HOST'] but that just returns the site that's being posted to. Does anyone know where in the Request object I can get the origin of the request?

As for getting the url from request (which is what I was looking for), use request.META['HTTP_REFERER'] instead.

In Django,
request.headers['Origin']
answers the original question.
You can print(request.headers) to see everything available in the headers.

Use this:
origin = request.META.get("HTTP_ORIGIN")
This is the way django-cors-headers use it in the middleware:

you can get it by request.META["HTTP_ORIGIN"]

I strongly advice you to use django-cors-headers. It lets you to define CORS_ORIGIN_WHITELIST which is a list of allowed origins in more pythonic way.

To answer the question "Does anyone know where in the Request object I can get the origin of the request?", would the request.META['REMOTE_ADDR'] give you what you need?

In Django 2.2 use:
request.META.get('HTTP_REFERER')
Make sure that the request property doesn't have mode = no-cors
see:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin
"There are some exceptions to the above rules; for example, if a cross-origin GET or HEAD request is made in no-cors mode, the Origin header will not be added."

Related

modify getJSON to work with CORS

I am looking for ways to allow cross-domain access using $.getJSON. I came across solutions which suggest that using CORS is the solution to this problem. But most of the solutions have a general ajax format.
I cannot use JSONP since I get data from a server which I do not have access. Is there a way to modify this code using $.getJSON to get the data?
$.getJSON(jsonURL, function(res){
console.log(JSON.stringify(res));
});
Or do I have to use ajax format for CORS?
Server which I do not have access
I think, this will break your neck.
You need some kind of access to the server or contact someone who has. At least you have to adjust the HTTP-Header to enter your domain Access-Control-Allow-Origin is the keyword.
Have a look at MDN
If you have access to set the HTTP Response Headers for the page that loads your JS scripts, then YES you can use CORS to send cross-domain requests. However, this is not supported in older browsers.
You need to set the Access-Control-Allow-Origin header, e.g.
Access-Control-Allow-Origin: *
Or
Access-Control-Allow-Origin: http://host-of-other-site.com
https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

How can I get HTTP response header using JS?

I tried so many tutorials online but everything I try is really old and fails - I can't even create an XMLHTTPRequest object!
I just want to get the header from google.com - how can I do that?
You would use xhr.getResponseHeader() to get a single header, or xhr.getAllResponseHeaders() to read all of the headers from an XMLHttpRequest response.
The reasons this won't work for you:
XMLHttpRequest is case sensitive. If you are using HTTP in all caps, it will fail.
Unless you are a google employee adding code to google.com, your request falls victim to the same origin policy. You'll have to use your server as a proxy to get headers from a google request.
You cant simply do this by JS. You'll have to use AJAX and do a server request to PHP,ASP, Java or whatever. The XMLHTTPRequest should do it - if you really want to do it manually. But it will really not work with foreign domains, so you are forced to do the XMLHTTTPRequest to a page on your server which will deliver the header.

How to get cross-domain data using Javascript in django?

Imagine, that you have two domains and you want them to interact through a Javascript mechanism.
So, what I've done so far is host two servers on different ports on my local machine. It seems that the request is being sent from one server to another, only it doesn't seem to return any data.
What do you think the problem is ? How can I solve it ?
P.S. Code examples would be greatly appreciated. Thank you.
I don't know about django, but the other domain must support CORS (see Wikipedia and the w3 spec).
Basically, the remote server must support the Access-Control-Allow-Origin header. Usually I just have my server set the header value to * to allow all origins to access data.
You might need to find more specific documentation for your particular webserver. You might also want to watch the conversation between servers using wireshark. It's a great little utility for finding out what's really happening with your HTTP requests/responses...
You need to add an extra header to host 2 to allow host 1. This site will help you http://enable-cors.org/
JSONP is about to solve cross domain issues:
http://en.wikipedia.org/wiki/JSONP
jQuery has good functionality to support JSONP,
(just some googled link of this topic)
http://sangers.nu/blog/tech/20090129-jsonp-with-jquery
EDIT:
JSONP could look a little weird than at first sight :) basically should support JSONP notation (call callback method, if it is provided). So, it checks if 'callback' method is provided and instead of returning results like
{ some: 12 }
It does,
callback( { some: 12 } )
Here is my blog post on that:
http://www.beletsky.net/2010/07/json-jsonp-and-same-origin-policy-issue.html
jsonp is your option infact I used a django snippet available here
http://djangosnippets.org/snippets/2208/

Is there any way to check is given link really exist?

For example there are lalalalaal.com that do NOT exist. Is there any way using JavaScript (possibly with jQuery) to check is given link really exist?
There has to be a server involved because of the Same Origin Policy — but it doesn't necessarily follow that it has to be your server. :-)
You can use a third-party service such as Yahoo to do the proxying for you as discussed here: "Using YQL as a proxy for cross-domain Ajax". That shows how to use jQuery to query YQL's JSON-P and JSON-P-X interfaces for another domain's content.
It's not complicated, from the article:
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=xml'&callback=?",
function(data){
if(data.results[0]){
container.html(data.results[0]);
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
}
);
There isn't, the response from another domain will always be null (the same origin policy applies here). You'd have to contact your own domain and have it check server-side if the site actually exists...but JavaScript alone can't do this.
No, there isn't.
In order to find out if a URL exists, you have to make a request to it and see if you get a response. The same origin policy prevents JavaScript, running in a browser under normal security conditions, from reading responses from different hosts.
I don't think you can, for security reasons (same domain policy).
Use AnyOrigin or the FOSS clone I made of it, WhateverOrigin.

jQuery ajax is making connection, but the response is blank?

i'm trying to make a test with ajax response using an external array as a config file...
But it isn't working, i'm getting always a blank response...
Can anyone point me the reason?
Here is the link of jsBin test: http://jsbin.com/udanu/2/edit
It looks like you have bumped into the Same Origin Policy. You cannot make Ajax requests to hosts outside your domain, unless you use JSONP, or some other technique to get around the policy.
You may want to check out the following Stack Overflow post for a few popular solutions to work around the SOP (mainly the JSONP, CORS and Reverse Proxy methods):
Ways to circumvent the same-origin policy
As you are trying to get data from another domain, maybe you should try using "jsonp" instead of "text" as a dataType.
EDIT: didn't see the previous answer.

Categories

Resources