On my website I have no login system. However, users get sessionid and csrftoken, but I need to clear them up from time to time
Is there any way that I can delete them manually?
Thanks a lot.
This is because django enables some middleware by default. This includes, django CSRF middleware and django session middleware. Remove them from your settings.py file
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
Related
I am using Angular 8 as frontend and Django 1.11.18 as backend. I am running my Angular project on https://127.0.0.1:4200 through command ng server --ssl true and Django API's are deployed on a separate redhat server and can be accessed through https://192.xxx.x.xx:7002/
My Login is a GET Request that returns success response with csrf token in header but cookies are not received on the browser at that time and when I call my POST request this cause "Forbidden" error due to CSRF Token.
Middleware in my settings.py is:
MIDDLEWARE = [
'Common.customMiddleware.ProcessRequest',
'django.middleware.security.SecurityMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
I have also added:
CSRF_TRUSTED_ORIGINS = ["127.0.0.1","192.xxx.x.xx"]
but still cookies are not received on the browser
Any kind of help will be appreciated. One thing more I would like to mention is that When I deploy the Angular project on the same server on which Django API's are applied then application works fine.
In django REST framework authentication middleware sets the user object in request ONLY after the views middleware is executed while any custom middleware is executed before that. is there someway to change this order and execute custom middleware AFTER user object is set by authentication middleware
As an alternative I create the user object in the middleware itself and it works fine but this is just a hack.
The middlewares as defined in common.py are:
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'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',
'application.middlewares.IPsBlockerMiddlewareHook',
'application.middlewares.UserMiddleware',
]
The custom middleware in question is UserMiddleware. I need it to be executed after authentication but doesnt seems to be the case
Middlewares are executed in the top to bottom order when the request comes and in bottom to top when the response is sent. You can specify your custom middleware after the authentication middleware and it will run after that.
I'm having a problem with the csrf token on a Django powered site, which I'm close to reporting as a bug.
Problem is basically, CSRF token fails when DEBUG is False. When DEBUG is False, if I'm using sessions for the csrf token (Django 1.11):
CSRF_USE_SESSIONS = True
CSRF_COOKIE_AGE = None
...all forms/post requests on the frontend fail authentication, but I can login fine to the Django admin panel, e.g., csrf token authentication succeeds.
On the other hand, if I'm using cookies for csrf, authentication on the frontend for forms/post requests go through without any problem, but then it fails for the admin login: CSRF verification failed. Request aborted.
Part of my settings.py file looks like this:
SECRET_KEY = os.getenv('DJANGO_SECRET_KEY')
DEBUG = 'DEBUG' in os.environ
# CSRF
# These are commented/uncommented depending on what method I'm testing
# CSRF_USE_SESSIONS = True
# CSRF_COOKIE_AGE = None
# I added the cookie domain setting after I started seeing the problem
# and hoped it would have resolved it; it didn't help.
CSRF_COOKIE_DOMAIN = '.{0}'.format(os.getenv('DOMAIN_NAME', 'mysite.com'))
ALLOWED_HOSTS = [
'.mysite.com',
'.mysite.info',
]
if DEBUG:
ALLOWED_HOSTS.extend(['.mysite.dev'])
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mainsite',
'constance',
'jstemplate',
'compressor',
]
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.gzip.GZipMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'mainsite.middleware.Guid',
'mainsite.middleware.SiteLang',
]
If I set DEBUG to True, I have no issues whatsoever with CSRF token authentication, both on the frontend as with logging into the Django admin panel.
I'm also using Redis as a cache. Am I missing something crucial that is causing this CSRF error? I must point out, there was a point in which I was not getting this error, but I cannot for the life of me pinpoint what change would have created this behavior with the CSRF token.
I also have the same issue.
I solve this by
1. pip install django-sslserver.
2. Put sslserver in the INSTALLED_APPS.
3. python manage.py runsslserver
I am using TokenAuthentication in Django REST Framework to have a script remotely access my API. The domain running the API is behind a TLS certificate.
I have scoured through MANY sources, and tried many options before coming here to figure out what my problem is. In short, I continue to get the CSRF verification failed. Request aborted. error when I attempt to post.
Here is my view:
# #csrf_exempt
#api_view(['POST'])
#authentication_classes((TokenAuthentication,))
#permission_classes((permissions.IsAuthenticated,))
def create_object(request):
csrf_exempt decorator has done nothing here. So, I have also tried it on my urls.py:
url(r'^create_object/', csrf_exempt(views.create_object),),
I even tried writing a custom decorator, and using this suggestion. Even when I do this, I cannot even seem to get that decorator to execute before getting the failure. Perhaps there is an issue with the ordering of my middleware?
'sslify.middleware.SSLifyMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'corsheaders.middleware.CorsPostCsrfMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.RemoteUserMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
Here are my django cors settings:
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = ('example.com',)
CORS_REPLACE_HTTPS_REFERER = True
As promised, here is the solution that I came up with. Admittedly, this is not perfect. I was not able to figure the underlying problem (why on HTTPS the app was not responding to csrf_exempt, or CORS_REPLACE_HTTPS_REFERER), but came up with this limited solution.
STEP 1
First, I subclassed the entire CsrfViewMiddleware class into my own version, and placed it into my middleware (changes from original quertion marked):
'sslify.middleware.SSLifyMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware', ##CHANGE
'myapp.csrf.CsrfViewMiddleware', ##CHANGE
'corsheaders.middleware.CorsPostCsrfMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.RemoteUserMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
At about line 160 of my version of CsrfViewMiddleware, I replaced the existing conditional to this:
acceptable_referers = ['https://%s' % u for u in settings.CORS_ORIGIN_WHITELIST] + ['http://%s' % u for u in settings.CORS_ORIGIN_WHITELIST]
if not same_origin(referer, good_referer) and referer not in acceptable_referers:
This got me past the invalid referer issue, which is fine because I am whitelisting the domains that are okay. It essentially comes to the same result as CORS_REPLACE_HTTPS_REFERER. My version cross-references the referer header with settings.CORS_ORIGIN_WHITELIST, while the CORS_REPLACE_HTTPS_REFERER method temporarily changes the request referer. Neither seems to me a sufficient enough security solution--but that is another conversation.
STEP 2
At this point, I was still getting the csrf cookie not found error. To circumvent this problem, and since csrf_exempt was not respoding (it seemed as if the middleware was executing too early), I added a new piece of middleware:
'sslify.middleware.SSLifyMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'myapp.csrf.CsrfSkipMiddleware' ##ADDED
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware', ##REMOVED
'myapp.csrf.CsrfViewMiddleware', ##ADDED
'corsheaders.middleware.CorsPostCsrfMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.RemoteUserMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
This new piece of middleware essentially sets a flag on the request object (_dont_enforce_csrf_checks) that already exists on the stock version of CsrfViewMiddleware and tells the script to ignore the rest of the csrf check. In order to do that, it checks the page path against a list of paths that I have selected to remove from csrf in settings.CSRF_SKIP_URLS.
class CsrfSkipMiddleware(object):
def process_request(self, request):
CSRF_SKIP_URLS = [re.compile(expr) for expr in settings.CSRF_SKIP_URLS]
path = request.path_info.lstrip('/')
if any(m.match(path) for m in CSRF_SKIP_URLS):
setattr(request, '_dont_enforce_csrf_checks', True)
THOUGHTS
Again, not the best implementation. But, for my purposes it works. Thoughts are still welcome.
I see you're using django cors headers.
I was facing a similar issue and specifying:
CORS_REPLACE_HTTPS_REFERER = True in settings.py resolved the problem.
I'm experiencing an issue with Django and Django Auth. From time to time the login page will not allow users to login. When the user presses login (on the /admin login form OR any custom login form) the page simply refreshes. After debugging further it seems that it is creating a session and then expiring it (somehow). Has anyone experienced this type of behavior with Django Auth?
Thanks,
cory
I haven't had this problem.
But so, you should check your apps, middleware, and context processor specifications in your settings.py file. You'll want to be sure the following are in place (in addition to whatever else you need for your specific app):
MIDDLEWARE_CLASSES = (
# ...
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
# ...
)
TEMPLATE_CONTEXT_PROCESSORS = (
# ...
"django.core.context_processors.auth",
"django.core.context_processors.request",
# ...
)
INSTALLED_APPS = (
# ...
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.sites',
# ...
)
... make sure that's all good to go and see if your problem persists. Good luck.