Django can't get user IP in AWS Elastic Beanstalk Load-Balanced Environment

Viewed 393

I have a load-balanced environment set up in AWS Elastic Beanstalk with a Django app deployed and running Django-user-sessions. I'd like it to be able to log the user session external IP addresses, but everything that gets logged is an internal IP. I have another environment that is not load-balanced and external user IPs are being collected, so I'm fairly sure the user IP is getting overwritten by the internal IP of the load balancer.

I have tried to install django-xforwardedfor-middleware which supposedly adds request.META['REMOTE_ADDR'] = request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip() to each request, but this has not solved the problem.

I also have an HTTPS engine rewrite in my .ebextensions that is not running on the environment that is working properly, but I don't think it is the problem:

files:
    "/etc/httpd/conf.d/ssl_rewrite.conf":
        mode: "000644"
        owner: root
        group: root
        content: |
            RewriteEngine On
            <If "-n '%{HTTP:X-Forwarded-Proto}' && %{HTTP:X-Forwarded-Proto} != 'https'">
            RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
            </If>

Are there any other things I could try to get django-user-sessions to collect external user IPs?

1 Answers

I found the problem: the positioning of x_forwarded_for.middleware.XForwardedForMiddleware matters. It should come before user_sessions.middleware.SessionMiddleware:

MIDDLEWARE = [
    ...
    'x_forwarded_for.middleware.XForwardedForMiddleware',
    'user_sessions.middleware.SessionMiddleware',  # the django-user-sessions middleware
    ...
]
Related