In my Django application, the following settings ensure that the response headers have the standard key-value pairs enabled.
However, the 'Server' name and version information is still visible by default which needs to be hidden (exposed server name and version is an OWASP vulnerability).
middleware.py
class MyAppMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
response['X-XSS-Protection'] = "1; mode=block"
return response
class RemoveHeaders(object): # this method invocation throws error
def process_response(self, request, response):
response['Server'] = ''
return response
Also as suggested in other posts, this middleware.py is declared in the first order of middlewares in settings.py:
MIDDLEWARE = [
'MyApp.middleware.RemoveHeaders',
'MyApp.middleware.MyAppMiddleware',
'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',
]
The RemoveHeaders() method throws error: TypeError: RemoveHeaders() takes no arguments. This is because I am unsure which object is being passed to this method.
Update: importing the following worked for me.
from django.utils.deprecation import MiddlewareMixin
# class to import in RemoveHeaders--
class RemoveHeaders(MiddlewareMixin):
# rest of the code

__call__, I added this lineprint('Response has Server header', response.has_header('Server'))which printedFalse. This means thatServerheader is not even set at that point. I am not sure where is it set and why does second method work.