Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1976 from peterbe/bug-989055-django-rate-limiting…
…-should-honor-x-forwarded-for-header-2 fixes bug 989055 - django rate limiting should honor x-forwarded-for
- Loading branch information
Showing
3 changed files
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
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. The | ||
# client's IP will be the first one. | ||
real_ip = real_ip.split(",")[0].strip() | ||
request.META['REMOTE_ADDR'] = real_ip |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters