Django-axes seems to ignore ipware settings behind Nginx

I'm struggling to set up my django-axes behind Nginx reverse proxy to take the HTTP_X_FORWARDED_FOR instead REMOTE_ADDR. I've tried all three variations as outlined here: https://django-axes.readthedocs.io/en/latest/4_configuration.html. I've tried setting the ipware fields in isolation as well as in combinations. Left-most and right-most also didn't make any difference., ip_address from Axes' attempts was always populated with REMOTE_ADDR.

I'm 100% sure that request.META contains both HTTP_X_FORWARDED_FOR as well as REMOTE_ADDR. I checked this by inserting a debugging middleware in front of axes. My logs show that both values are valid and I can manipulate the IP logged by Axes by modifying REMOTE_ADDR in my middleware:

class OverwriteRemoteAddrMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        logger = logging.getLogger('django.request')
        xff = request.META.get('HTTP_X_FORWARDED_FOR')
        logger.info(f"[Middleware] Before: HTTP_X_FORWARDED_FOR={xff}, REMOTE_ADDR={request.META.get('REMOTE_ADDR')}")
        # Set REMOTE_ADDR to a fixed unrelated value for testing
        request.META['REMOTE_ADDR'] = None
        logger.info(f"[Middleware] After: REMOTE_ADDR={request.META['REMOTE_ADDR']}, X-Forwarded-For={xff}")
        return self.get_response(request)

This is my full settings.py that I'm currently using in a minimal django test project:

"""
Django settings for django_test project.

Generated by 'django-admin startproject' using Django 6.0.1.
"""

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'django-insecure-a8_oxq6w3m()1fh)%)srfm!prh_#4tsp3(kc2+37_@krm_++$%'
DEBUG = True
ALLOWED_HOSTS = ['*']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'axes',
    'app',
]

MIDDLEWARE = [
    'axes.middleware.AxesMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'django_test.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'django_test.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

AUTH_PASSWORD_VALIDATORS = []

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
STATIC_URL = 'static/'

# Axes minimal config
AXES_ENABLED = True
AUTHENTICATION_BACKENDS = [
    'axes.backends.AxesStandaloneBackend',
    'django.contrib.auth.backends.ModelBackend',
]
"""
Django settings for django_test project.

Generated by 'django-admin startproject' using Django 6.0.1.

For more information on this file, see
https://docs.djangoproject.com/en/6.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/6.0/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/6.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-a8_oxq6w3m()1fh)%)srfm!prh_#4tsp3(kc2+37_@krm_++$%'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

        'axes',
        'app',
    ]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# Add OverwriteRemoteAddrMiddleware before AxesMiddleware for testing
MIDDLEWARE = ['app.middleware.OverwriteRemoteAddrMiddleware', 'axes.middleware.AxesMiddleware'] + MIDDLEWARE

ROOT_URLCONF = 'django_test.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'django_test.wsgi.application'


# Database
# https://docs.djangoproject.com/en/6.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/6.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/6.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/6.0/howto/static-files/

STATIC_URL = 'static/'
    
AXES_ENABLED = True
AXES_FAILURE_LIMIT = 99999999  
AXES_HANDLER = 'axes.handlers.database.AxesDatabaseHandler'

USE_X_FORWARDED_HOST = True
AXES_USE_X_FORWARDED_FOR = True
AXES_X_FORWARDED_FOR_HEADER = 'X-Forwarded-For'

AXES_TRUSTED_PROXIES = ['*']

AXES_IPWARE_PROXY_COUNT =1

AXES_IPWARE_PROXY_ORDER = [
    'HTTP_X_FORWARDED_FOR',
    'REMOTE_ADDR',
]

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

AUTHENTICATION_BACKENDS = [
    'axes.backends.AxesStandaloneBackend',
    'django.contrib.auth.backends.ModelBackend',
]

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
        'axes_file': {
            'class': 'logging.FileHandler',
            'filename': 'axes_debug.log',
            'mode': 'a',
            'formatter': 'verbose',
        },
    },
    'formatters': {
        'verbose': {
            'format': '[{asctime}] {levelname} {name}: {message}',
            'style': '{',
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['console', 'axes_file'],
            'level': 'INFO',
            'propagate': False,
        },
    },
}
Вернуться на верх