Forbidden (403) CSRF verification failed. Request aborted.

7,367 views
Skip to first unread message

Mangirdas Grinius

unread,
Dec 18, 2019, 1:57:35 AM12/18/19
to NetBox
Hello,

I would like to get any help regarding this case. I changed my web from http to https and now I can't login into my web. For example web is working, but if I try login I am getting this error

Forbidden (403)

CSRF verification failed. Request aborted.

Help

Reason given for failure:

    Referer checking failed - https://netbox.gfin.gf.lt:8085/login/?next=/ does not match any trusted origins.
    

In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:

  • Your browser is accepting cookies.
  • The view function passes a request to the template's render method.
  • In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
  • If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
  • The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.

You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.


My nginx configuration looks like:
server {
    listen 8085 ssl;
    server_name netbox.gfin.gf.lt;
    ssl_certificate /etc/nginx/ssl/netbox.pem;
    ssl_certificate_key /etc/nginx/ssl/netbox.pem;
    include ssl_config/ssl_config.conf;
    client_max_body_size 25m;

    location /static/ {
        alias /opt/netbox/netbox/static/;
    }

    location / {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
    }
}

My server Settings:

SettingValue
ABSOLUTE_URL_OVERRIDES{}
ADMINS[]
ALLOWED_HOSTS['netbox.gfin.gf.lt']
APPEND_SLASHTrue
AUTHENTICATION_BACKENDS['utilities.auth_backends.ViewExemptModelBackend']
AUTH_PASSWORD_VALIDATORS'********************'
AUTH_USER_MODEL'auth.User'
BANNER_BOTTOM''
BANNER_LOGIN''
BANNER_TOP''
BASE_DIR'/opt/netbox/netbox'
BASE_PATH''
CACHEOPS{'auth.*': {'ops': ('fetch', 'get')}, 'auth.permission': {'ops': 'all'}, 'auth.user': {'ops': 'get', 'timeout': 900}, 'circuits.*': {'ops': 'all'}, 'dcim.*': {'ops': 'all'}, 'extras.*': {'ops': 'all'}, 'ipam.*': {'ops': 'all'}, 'secrets.*': '********************', 'tenancy.*': {'ops': 'all'}, 'users.*': {'ops': 'all'}, 'virtualization.*': {'ops': 'all'}}
CACHEOPS_DEFAULTS{'timeout': 900}
CACHEOPS_DEGRADE_ON_FAILURETrue
CACHEOPS_ENABLEDTrue
CACHEOPS_REDIS'redis://localhost:6379/1'
CACHES{'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}
CACHE_MIDDLEWARE_ALIAS'default'
CACHE_MIDDLEWARE_KEY_PREFIX'********************'
CACHE_MIDDLEWARE_SECONDS600
CACHE_TIMEOUT900
CHANGELOG_RETENTION90
CORS_ORIGIN_ALLOW_ALLTrue
CORS_ORIGIN_REGEX_WHITELIST[]
CORS_ORIGIN_WHITELIST['https://netbox.gfin.gf.lt']
CSRF_COOKIE_AGE31449600
CSRF_COOKIE_DOMAINNone
CSRF_COOKIE_HTTPONLYFalse
CSRF_COOKIE_NAME'csrftoken'
CSRF_COOKIE_PATH'/'
CSRF_COOKIE_SAMESITE'Lax'
CSRF_COOKIE_SECUREFalse
CSRF_FAILURE_VIEW'django.views.csrf.csrf_failure'
CSRF_HEADER_NAME'HTTP_X_CSRFTOKEN'
CSRF_TRUSTED_ORIGINS['netbox.gfin.gf.lt']
CSRF_USE_SESSIONSFalse
DATABASE{'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'ENGINE': 'django.db.backends.postgresql', 'HOST': 'localhost', 'NAME': 'netbox', 'OPTIONS': {}, 'PASSWORD': '********************', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIRROR': None, 'NAME': None}, 'TIME_ZONE': None, 'USER': 'netbox'}
DATABASES{'default': {'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'ENGINE': 'django.db.backends.postgresql', 'HOST': 'localhost', 'NAME': 'netbox', 'OPTIONS': {}, 'PASSWORD': '********************', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIRROR': None, 'NAME': None}, 'TIME_ZONE': None, 'USER': 'netbox'}}
DATABASE_ROUTERS[]
DATA_UPLOAD_MAX_MEMORY_SIZE2621440
DATA_UPLOAD_MAX_NUMBER_FIELDSNone
DATETIME_FORMAT'N j, Y g:i a'
DATETIME_INPUT_FORMATS['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M:%S.%f', '%m/%d/%Y %H:%M', '%m/%d/%Y', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M:%S.%f', '%m/%d/%y %H:%M', '%m/%d/%y']
DATE_FORMAT'N j, Y'
DATE_INPUT_FORMATS['%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', '%b %d %Y', '%b %d, %Y', '%d %b %Y', '%d %b, %Y', '%B %d %Y', '%B %d, %Y', '%d %B %Y', '%d %B, %Y']
DEBUGTrue
DEBUG_PROPAGATE_EXCEPTIONSFalse
DECIMAL_SEPARATOR'.'
DEFAULT_CHARSET'utf-8'
DEFAULT_CONTENT_TYPE'text/html'
DEFAULT_EXCEPTION_REPORTER_FILTER'django.views.debug.SafeExceptionReporterFilter'
DEFAULT_FILE_STORAGE'django.core.files.storage.FileSystemStorage'
DEFAULT_FROM_EMAIL'webmaster@localhost'
DEFAULT_INDEX_TABLESPACE''
DEFAULT_TABLESPACE''
DISALLOWED_USER_AGENTS[]
EMAIL{'FROM_EMAIL': '', 'PASSWORD': '********************', 'PORT': 25, 'SERVER': 'localhost', 'TIMEOUT': 10, 'USERNAME': ''}
EMAIL_BACKEND'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST'localhost'
EMAIL_HOST_PASSWORD'********************'
EMAIL_HOST_USER''
EMAIL_PORT25
EMAIL_SSL_CERTFILENone
EMAIL_SSL_KEYFILE'********************'
EMAIL_SUBJECT_PREFIX'[NetBox] '
EMAIL_TIMEOUT10
EMAIL_USE_LOCALTIMEFalse
EMAIL_USE_SSLFalse
EMAIL_USE_TLSFalse
ENFORCE_GLOBAL_UNIQUEFalse
EXEMPT_VIEW_PERMISSIONS[]
FILE_CHARSET'utf-8'
FILE_UPLOAD_DIRECTORY_PERMISSIONSNone
FILE_UPLOAD_HANDLERS['django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler']
FILE_UPLOAD_MAX_MEMORY_SIZE2621440
FILE_UPLOAD_PERMISSIONSNone
FILE_UPLOAD_TEMP_DIRNone
FILTERS_NULL_CHOICE_LABEL'None'
FILTERS_NULL_CHOICE_VALUE'null'
FIRST_DAY_OF_WEEK0
FIXTURE_DIRS[]
FORCE_SCRIPT_NAMENone
FORMAT_MODULE_PATHNone
FORM_RENDERER'django.forms.renderers.DjangoTemplates'
HOSTNAME'netbox.gfin.gf.lt'
IGNORABLE_404_URLS[]
INSTALLED_APPS['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'cacheops', 'corsheaders', 'debug_toolbar', 'django_filters', 'django_tables2', 'django_prometheus', 'mptt', 'rest_framework', 'taggit', 'taggit_serializer', 'timezone_field', 'circuits', 'dcim', 'ipam', 'extras', 'secrets', 'tenancy', 'users', 'utilities', 'virtualization', 'drf_yasg']
INTERNAL_IPS('127.0.0.1', '::1')

LANGUAGES_BIDI['he', 'ar', 'fa', 'ur']
LANGUAGE_CODE'en-us'
LANGUAGE_COOKIE_AGENone
LANGUAGE_COOKIE_DOMAINNone
LANGUAGE_COOKIE_NAME'django_language'
LANGUAGE_COOKIE_PATH'/'
LDAP_CONFIGNone
LOCALE_PATHS[]
LOGGING{}
LOGGING_CONFIG'logging.config.dictConfig'
LOGIN_REDIRECT_URL'/accounts/profile/'
LOGIN_REQUIREDFalse
LOGIN_TIMEOUTNone
LOGIN_URL'/login/'
LOGOUT_REDIRECT_URLNone
MAINTENANCE_MODEFalse
MANAGERS[]
MAX_PAGE_SIZE1000
MEDIA_ROOT'/opt/netbox/netbox/media'
MEDIA_URL'/media/'
MESSAGE_STORAGE'django.contrib.messages.storage.fallback.FallbackStorage'
MESSAGE_TAGS{40: 'danger'}
METRICS_ENABLEDFalse
MIDDLEWARE('debug_toolbar.middleware.DebugToolbarMiddleware', 'django_prometheus.middleware.PrometheusBeforeMiddleware', 'corsheaders.middleware.CorsMiddleware', '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', 'django.middleware.security.SecurityMiddleware', 'utilities.middleware.ExceptionHandlingMiddleware', 'utilities.middleware.LoginRequiredMiddleware', 'utilities.middleware.APIVersionMiddleware', 'extras.middleware.ObjectChangeMiddleware', 'django_prometheus.middleware.PrometheusAfterMiddleware')
MIGRATION_MODULES{}
MONTH_DAY_FORMAT'F j'
NAPALM_ARGS{}
NAPALM_PASSWORD'********************'
NAPALM_TIMEOUT30
NAPALM_USERNAME''
NUMBER_GROUPING0
PAGINATE_COUNT50
PASSWORD_HASHERS'********************'
PASSWORD_RESET_TIMEOUT_DAYS'********************'
PER_PAGE_DEFAULTS[25, 50, 100, 250, 500, 1000]
PREFER_IPV4False
PREPEND_WWWFalse
PROMETHEUS_EXPORT_MIGRATIONSFalse
REDIS{'CACHE_DATABASE': 1, 'DATABASE': 0, 'DEFAULT_TIMEOUT': 300, 'HOST': 'localhost', 'PASSWORD': '********************', 'PORT': 6379, 'SSL': False}
REDIS_CACHE_CON_STRING'redis://localhost:6379/1'
REDIS_CACHE_DATABASE1
REDIS_DATABASE0
REDIS_DEFAULT_TIMEOUT300
REDIS_HOST'localhost'
REDIS_PASSWORD'********************'
REDIS_PORT6379
REDIS_SSLFalse
REPORTS_ROOT'/opt/netbox/netbox/reports'
REST_FRAMEWORK{'ALLOWED_VERSIONS': ['2.6'], 'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework.authentication.SessionAuthentication', 'netbox.api.TokenAuthentication'), 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 'DEFAULT_PAGINATION_CLASS': 'netbox.api.OptionalLimitOffsetPagination', 'DEFAULT_PERMISSION_CLASSES': ('netbox.api.TokenPermissions',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer', 'netbox.api.FormlessBrowsableAPIRenderer'), 'DEFAULT_VERSION': '2.6', 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.AcceptHeaderVersioning', 'PAGE_SIZE': 50, 'VIEW_NAME_FUNCTION': 'netbox.api.get_view_name'}
REST_FRAMEWORK_VERSION'2.6'
ROOT_URLCONF'netbox.urls'
RQ_QUEUES{'default': {'DB': 0, 'DEFAULT_TIMEOUT': 300, 'HOST': 'localhost', 'PASSWORD': '********************', 'PORT': 6379, 'SSL': False}}
SCRIPTS_ROOT'/opt/netbox/netbox/scripts'
SECRETS_MIN_PUBKEY_SIZE'********************'
SECRET_KEY'********************'
SECURE_BROWSER_XSS_FILTERFalse
SECURE_CONTENT_TYPE_NOSNIFFFalse
SECURE_HSTS_INCLUDE_SUBDOMAINSFalse
SECURE_HSTS_PRELOADFalse
SECURE_HSTS_SECONDS0
SECURE_PROXY_SSL_HEADER('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_REDIRECT_EXEMPT[]
SECURE_SSL_HOSTNone
SECURE_SSL_REDIRECTFalse
SERVER_EMAIL''
SESSION_CACHE_ALIAS'default'
SESSION_COOKIE_AGE1209600
SESSION_COOKIE_DOMAINNone
SESSION_COOKIE_HTTPONLYTrue
SESSION_COOKIE_NAME'sessionid'
SESSION_COOKIE_PATH'/'
SESSION_COOKIE_SAMESITE'Lax'
SESSION_COOKIE_SECUREFalse
SESSION_ENGINE'django.contrib.sessions.backends.db'
SESSION_EXPIRE_AT_BROWSER_CLOSEFalse
SESSION_FILE_PATHNone
SESSION_SAVE_EVERY_REQUESTFalse
SESSION_SERIALIZER'django.contrib.sessions.serializers.JSONSerializer'
SETTINGS_MODULE'netbox.settings'
SHORT_DATETIME_FORMAT'Y-m-d H:i'
SHORT_DATE_FORMAT'Y-m-d'
SHORT_TIME_FORMAT'H:i:s'
SIGNING_BACKEND'django.core.signing.TimestampSigner'
SILENCED_SYSTEM_CHECKS[]
STATICFILES_DIRS('/opt/netbox/netbox/project-static',)
STATICFILES_FINDERS['django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder']
STATICFILES_STORAGE'django.contrib.staticfiles.storage.StaticFilesStorage'
STATIC_ROOT'/opt/netbox/netbox/static'
STATIC_URL'/static/'
SWAGGER_SETTINGS{'DEFAULT_AUTO_SCHEMA_CLASS': 'utilities.custom_inspectors.NetBoxSwaggerAutoSchema', 'DEFAULT_FIELD_INSPECTORS': ['utilities.custom_inspectors.NullableBooleanFieldInspector', 'utilities.custom_inspectors.CustomChoiceFieldInspector', 'utilities.custom_inspectors.TagListFieldInspector', 'utilities.custom_inspectors.SerializedPKRelatedFieldInspector', 'drf_yasg.inspectors.CamelCaseJSONFilter', 'drf_yasg.inspectors.ReferencingSerializerInspector', 'drf_yasg.inspectors.RelatedFieldInspector', 'drf_yasg.inspectors.ChoiceFieldInspector', 'drf_yasg.inspectors.FileFieldInspector', 'drf_yasg.inspectors.DictFieldInspector', 'drf_yasg.inspectors.SerializerMethodFieldInspector', 'drf_yasg.inspectors.SimpleFieldInspector', 'drf_yasg.inspectors.StringDefaultFieldInspector'], 'DEFAULT_FILTER_INSPECTORS': ['utilities.custom_inspectors.IdInFilterInspector', 'drf_yasg.inspectors.CoreAPICompatInspector'], 'DEFAULT_MODEL_DEPTH': 1, 'DEFAULT_PAGINATOR_INSPECTORS': ['utilities.custom_inspectors.NullablePaginatorInspector', 'drf_yasg.inspectors.DjangoRestResponsePagination', 'drf_yasg.inspectors.CoreAPICompatInspector'], 'SECURITY_DEFINITIONS': {'Bearer': {'in': 'header', 'name': 'Authorization', 'type': 'apiKey'}}, 'VALIDATOR_URL': None}
TEMPLATES[{'APP_DIRS': True, 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/opt/netbox/netbox/templates'], 'OPTIONS': {'context_processors': ['django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.media', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'utilities.context_processors.settings']}}]
TEMPLATES_DIR'/opt/netbox/netbox/templates'
TEST_NON_SERIALIZED_APPS[]
TEST_RUNNER'django.test.runner.DiscoverRunner'
THOUSAND_SEPARATOR','
TIME_FORMAT'g:i a'
TIME_INPUT_FORMATS['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']
TIME_ZONE'UTC'
USE_I18NTrue
USE_L10NFalse
USE_THOUSAND_SEPARATORFalse
USE_TZTrue
USE_X_FORWARDED_HOSTTrue
USE_X_FORWARDED_PORTFalse
VERSION'2.6.9'
WEBHOOKS_ENABLEDFalse
WSGI_APPLICATION'netbox.wsgi.application'
X_FRAME_OPTIONS'SAMEORIGIN'
YEAR_MONTH_FORMAT'F Y'


Heinz Meier

unread,
Dec 25, 2019, 9:04:15 AM12/25/19
to NetBox
Hi,

it seems I ran into the same error. Did you find any solution already?

Michael

Heinz Meier

unread,
Dec 26, 2019, 8:24:42 AM12/26/19
to NetBox
The part of the configuration.py, I changed:

ALLOWED_HOSTS = ['mgmt01.exampe.org', '[2001:xxxx:xxxx:xxxx::1:24]', '[::1]', 'netbox.example.org' ]
DATABASE = {
    'NAME': 'netbox',         # Database name
    'USER': 'netbox',         # PostgreSQL username
    'PASSWORD': 'XXXX',           # PostgreSQL password
    'HOST': 'localhost',      # Database server
    'PORT': '',               # Database port (leave blank for default)
    'CONN_MAX_AGE': 300,      # Max database connection age
}
SECRET_KEY = 'XXXX'


The server section of the nginx.conf:

    server {
                listen 80;
                listen [::]:80;
                # listen [::]:443 ssl;
                # listen 443 ssl;
                server_name netbox.example.org;
                ssl_certificate /etc/nginx/ssl/mgmt01.pem;
                ssl_certificate_key /etc/nginx/ssl/mgmt01.key;

                client_max_body_size 25m;
                location /static/ {
                        alias /opt/netbox/netbox/static/;
                }
                location / {
                        proxy_pass http://127.0.0.1:8001;
                        proxy_set_header X-Forwarded-Host $server_name;
                        proxy_set_header X-Real-IP $remote_addr;
                        proxy_set_header X-Forwarded-Proto $scheme;
                }
    }

If Is comment the listen .. 80 and uncomment the ssl listeners, I get the error. I have a self-signed certificate with Issuer and Subject:

Subject: C = XX, ST = XXX, L = XXX, O = XXXX, CN = netbox.example.org, emailAddress = "sysmaster <sysm...@example.org>"

On my client I have added netbox.example.org in my /etc/hosts.

Michael
Message has been deleted

Mangirdas Grinius

unread,
Dec 27, 2019, 3:48:36 AM12/27/19
to NetBox
Nope, I didn't resolve this issue. I reverted all configuration and now I am using HTTP. Maybe you solved this issue?

Heinz Meier

unread,
Dec 27, 2019, 8:37:04 AM12/27/19
to NetBox
Found the solution. In nginx.conf my location section now look like:

                location / {
                        proxy_pass http://127.0.0.1:8001;
                        # proxy_set_header X-Forwarded-Host $server_name;
                        proxy_set_header X-Real-IP $remote_addr;
                        proxy_set_header Host $host;
                        # proxy_set_header X-Forwarded-Proto $scheme;
                        proxy_pass_header X-XSRF-TOKEN;
                }

Brian Candler

unread,
Dec 28, 2019, 6:50:48 AM12/28/19
to NetBox
It would be interesting to know why it originally worked for http but not https.

I also note from the nginx documentation that proxy_pass_request_headers defaults to "on", so it *should* have been passing the X-XSRF-Token and Host headers automatically.  Could there be some other part of the nginx config where this is turned off?

Mangirdas Grinius

unread,
Dec 30, 2019, 1:40:05 AM12/30/19
to NetBox
Thank you very much! this solution works like a charm!

Ioannis Theodoridis

unread,
Jan 24, 2020, 7:53:28 AM1/24/20
to NetBox
Hello all.
I am afraid that I am having the same issue and the solution provided by Heinz Meier doesn't work for me.
I am working on netbox 2.7.2 (latest). In my case, if I serve content with http (80) everything works fine, including local and LDAP logins, but if I enable the https (443) listener (and deactivate the http one) then the above problem occurs.
If I try the solution provided by Heinz, then I get back a 400 Message (Bad Request). This keeps happening as long as I don't uncomment the # proxy_set_header X-Forwarded-Proto $scheme; line. If I do uncomment it, then the initial problem continues (the addition of proxy_pass_header X-XSRF-TOKEN; line makes no difference).
Any other ideas?

Mangirdas Grinius

unread,
Jan 29, 2020, 2:29:15 AM1/29/20
to NetBox
please put your configuration

Vivek Janjrukiya

unread,
Jul 5, 2021, 5:48:47 PM7/5/21
to NetBox
Hello, 

I am having Netbox 2.11.2 and having the same issue. i changed the setting of nginx exactly what is mentioned above but still having the same issue. can someone help?

Reply all
Reply to author
Forward
0 new messages