简体   繁体   中英

Getting the request origin in a Django request

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?

至于从request中获取 url(这是我正在寻找的),请改用request.META['HTTP_REFERER']

In Django,

request.headers['Origin']

answers the original question.

You can print(request.headers) to see everything available in the headers.

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.

要回答“有谁知道我可以在 Request 对象中的什么位置获取请求的来源?”这个问题,request.META['REMOTE_ADDR'] 会满足您的需求吗?

你可以通过 request.META{"HTTP_ORIGIN"]

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."

Use this:

origin = request.META.get("HTTP_ORIGIN")

This is the way django-cors-headers use it in the middleware :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM