diff options
| author | Adrian Holovaty <adrian@holovaty.com> | 2006-08-18 03:12:36 +0000 |
|---|---|---|
| committer | Adrian Holovaty <adrian@holovaty.com> | 2006-08-18 03:12:36 +0000 |
| commit | 8f065bba6b262fe7b1bfde15e70bcbc7e4602a48 (patch) | |
| tree | b7d073f9e8d31a74a62d2fe9a2fe42727a0c2251 /django/middleware/http.py | |
| parent | efa19ae8a78d555e826dc7bbbfa1c20c3475e498 (diff) | |
Fixed #2552 -- Added SetRemoteAddrFromForwardedFor middleware and documentation. Thanks, Ian Holsman
git-svn-id: http://code.djangoproject.com/svn/django/trunk@3602 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'django/middleware/http.py')
| -rw-r--r-- | django/middleware/http.py | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/django/middleware/http.py b/django/middleware/http.py index 12d0c0f683..3ebd8ffd1a 100644 --- a/django/middleware/http.py +++ b/django/middleware/http.py @@ -35,3 +35,27 @@ class ConditionalGetMiddleware(object): response.content = '' return response + +class SetRemoteAddrFromForwardedFor(object): + """ + Middleware that sets REMOTE_ADDR based on HTTP_X_FORWARDED_FOR, if the + latter is set. This is useful if you're sitting behind a reverse proxy that + causes each request's REMOTE_ADDR to be set to 127.0.0.1. + + Note that this does NOT validate HTTP_X_FORWARDED_FOR. If you're not behind + a reverse proxy that sets HTTP_X_FORWARDED_FOR automatically, do not use + this middleware. Anybody can spoof the value of HTTP_X_FORWARDED_FOR, and + because this sets REMOTE_ADDR based on HTTP_X_FORWARDED_FOR, that means + anybody can "fake" their IP address. Only use this when you can absolutely + trust the value of HTTP_X_FORWARDED_FOR. + """ + def process_request(self, request): + try: + real_ip = request.META['HTTP_X_FORWARDED_FOR'] + except KeyError: + return None + else: + # HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs. + # Take just the first one. + real_ip = real_ip.split(",")[0] + request.META['REMOTE_ADDR'] = real_ip |
