Django sessions not working in Internet Explorer - django

Sessions work perfectly in all other browsers that I have tested.
If I try to get the session id with sessionid = request.COOKIES['sessionid'], I get this error: KeyError: 'sessionid'
This is what I have in my settings.py:
CACHE_BACKEND = 'memcached://127.0.0.1:11211/'
SESSION_COOKIE_DOMAIN = '.vb.is'
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
Sites are vb.is, fiskifrettir.vb.is and hestabladid.vb.is
Server setup is: apache2 (mod_wsgi) and nginx

Setting a cookie on XX.XX won't work in general. See Q#6 here: http://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx and see http://blogs.msdn.com/b/ieinternals/archive/2009/09/19/private-domain-names-and-public-suffixes-in-internet-explorer.aspx.
You can avoid the problem by setting the cookie with domain=WWW.vb.is instead.

Related

allowed_host changes not effective

I've got an address say example.com and have added it to the allowed_hosts list. But when I access the site I get
ALLOWED_HOSTS ['127.0.0.1', '::1', '178.XX.XX.XXX', 'xx80::xx81:xxx:xx3x:x12x%eth0']
in the debug error page, while the actual settings.py file reads ['178.XX.XX.XXX','example.com']. I figured the changes to settings.py aren't registered as I can remove 178.XX.XX.XXX from the list and still access the site (after clearing the browser cache) I've restarted nginx, gunicorn and the whole server to no avail. The whole thing is set up on ubuntu 16.04 running django 1.8 and using nginx and gunicorn. Any ideas where this override of allowed_hosts could be coming from?
Ok this is embarassing but the One-cick install for django on 16.04 from Digital Ocean adds a line at the very end of settings.py where ALLOWED_HOSTS is redefined.
# Find out what the IP addresses are at run time
# This is necessary because otherwise Gunicorn will reject the connections
def ip_addresses():
ip_list = []
for interface in netifaces.interfaces():
addrs = netifaces.ifaddresses(interface)
for x in (netifaces.AF_INET, netifaces.AF_INET6):
if x in addrs:
ip_list.append(addrs[x][0]['addr'])
return ip_list
# Discover our IP address
ALLOWED_HOSTS = ip_addresses()
ALLOWED_HOSTS.append('.example.com') #I added this line
So adding an append to the line fixes the problem.

Error "You're accessing the development server over HTTPS, but it only supports HTTP"

When I try to write the server link like http:// .... it redirects to https:// and in the terminal :
message Bad HTTP/0.9 request type ('\x16\x03\x01\x00\x8b\x01\x00\x00\x87\x03\x01Ð\x118¿JÄ\x19[Òç\x01<O')
You're accessing the development server over HTTPS, but it only supports HTTP.
I think you should create different settings.py ( base_settings.py, local_settings.py, production_settings.py). And in your settings.py do something like this:
import socket
if socket.gethostname()=="Raouf-PC":
from local_settings import *
Change 'Raouf-PC' to the hostname of your PC.
P:S: I'm using Windows 10.
After doing that place the below data in your production_settings.py and save. Then clear your browser cache and visit your site in development server.
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
If the above doesn't suit your needs, then in your local_settings.py paste the below data, save and clear your browser cache and visit your site.
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
SECURE_SSL_REDIRECT = False
Note: at the beginning of production_setttings.py and local_settings.py put:
from base_settings.py import *
Your base settings should contain 'settings' that will be used both on local and production server so you won't be repeating it everytime.
P:S If my answer is accepted, I dedicate it to the good people on SO who have helped me in one way or the other. This is my first time of answering a question. I hope to do more in the future. :)
You probably have the setting SECURE_SSL_REDIRECT set to True
This setting should be False when running the development server
Instead of using the command
python manage.py runserver
I used
python manage.py runserver 8080
Just by changing the port number, it is working for me.
CORS_REPLACE_HTTPS_REFERER = False
HOST_SCHEME = "http://"
SECURE_PROXY_SSL_HEADER = None
SECURE_SSL_REDIRECT = False
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
SECURE_HSTS_SECONDS = None
SECURE_HSTS_INCLUDE_SUBDOMAINS = False
SECURE_FRAME_DENY = False
1. Put this settings at the end of your settings.py
2. Clear your browser cache and then run your project.
If you are part of a team, you can use a variable to set the development environment. I use DJANGO_DEV=development
for e.g., on the computer that will be used for development, you add this to your ~/.bashrc file:
export DJANGO_DEV=true
or you can use django-environ
After that you can check, if current environment is a DEV env and set the specific values.
import os
if os.environ.get('DJANGO_ENV') is not None:
SECURE_SSL_REDIRECT = False
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
else:
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
If there are multiple settings, that you can go and define specific files as described in #yoyo's answer.
Simply change the path in your .env file to http://localhost:8000/
It worked for me. I'm using the Django backend and React frontend with the Django rest framework.
Nothing above helped me so digged in setting.py and
changed this to ACCOUNT_DEFAULT_HTTP_PROTOCOL = "https"
this ACCOUNT_DEFAULT_HTTP_PROTOCOL = "http"
it fixed the problem for me hope it helps
I also recommend to be sure that you are not trying access page by some port. For example by running Django server on PyCharm with some port.
Insert the below configs at the end of your settings.py file or completely comment them out(if you already had)
SECURE_CONTENT_TYPE_NOSNIFF = False
SECURE_BROWSER_XSS_FILTER = False
SECURE_SSL_REDIRECT = False
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
X_FRAME_OPTIONS = 'DENY'
then-,
2. Clear your browser cache and then re-run your project.
its clearly telling that you are accessing development server over https, but it only supports http.
usually we access development server like http://127.0.0.1:8000 but in your case its https://127.0.0.1:8000 as it's mentioned we cannot access development server over https.
I have gone through the same problem, but in my case when I was sending the email verification to gmail account, I was sending endpoint as https://127.0.0.1:8000/verify. https was used instead of http, so I corrected it to http then it worked fine.
Check the Django's site URL. It may have https.
Disable following variables in settings.py or .env
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
CSRF_TRUSTED_ORIGINS = ['yoursite.com']
Set DEBUG as True
DEBUG = True
Clear the Django site's(what you developed) cookies and sessions on the browser. For Google Chrome, steps are below.
Settings-> Privacy and Security -> Cookies and other site data -> See all cookies and site data -> Search your site name or IP and click 'Trash' icon.
Close the browser and reload the site now.

Admin redirects to /login although REMOTE_USER is provided

I configured Authentication using REMOTE_USER in a Django project, replacing the default ModelBackend. However, when I call an admin page it still redirects to the login page. I tested with:
curl -i -H 'REMOTE_USER: ruser1' http://localhost:8765/admin/myapp/mytable/
Location: http://localhost:8765/admin/login/?next=/admin/myapp/mytable/
[edit: this is wrong - I tested as well with
REMOTE_USER=ruser1 ./manage.py runserver]
The remote user has been added to the auth_user table.
My related config snippets are:
MIDDLEWARE_CLASSES = (
...
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.RemoteUserMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
...
)
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.RemoteUserBackend',
)
You can't set REMOTE_USER as an HTTP header, otherwise users would be able to spoof the header and log in as any user they wanted.
In production, the REMOTE_USER environment variable is set by the server, e.g. Apache or Nginx. If you are testing using the development server, you can set the remote user with
REMOTE_USER=ruser1 ./manage.py runserver
Any requests to the dev server will be processed with ruser1 as the logged in user.

Django and Bad Request (400)

I created new django project;
added to my settings.py:
DEBUG = False
ALLOWED_HOSTS= [
'localhost',
'my_site.com'
]
created app test_view;
added hello_world to test_view.views
from django.http.response import HttpResponse
def hello_world(request):
return HttpResponse('Hello World!!!')
added test route to urls.py url(r'test/', 'test_view.views.hello_world');
fixed /etc/hosts
127.0.0.1 localhost my_site.com
Now when i'm trying to access http://my_site.com:8000/test/ django returns Bad Request (400). But when url is http://localhost:8000/test/ I can see my Hello World page. What can be wrong?
UPD:
The same result with DEBUG = True
UPD2:
One more working hostname is ubuntu-virtualbox (computer's name).
But even when I changed computer's name to my_site, ubuntu-virtualbox was still available and my_site returned Bad Request (400)
May it be because of some system settings? (it's clean ubuntu in virtualbox).
Or maybe problem in virtualenv? Is there a way to trace the error?
It might be a bad Cookie. Try deleting them.
It looks like django can see if request isn't passed through dns server. Installation and configuration of bind9 instead of changes in /etc/hosts solved this problem.
You need another line in your hosts file.
127.0.0.1 localhost
127.0.0.1 my_site.com
Then in your ALLOWED_HOSTS...
ALLOWED_HOSTS = [
'localhost',
'.my_site.com', # not 'my_site.com'
]
ALSO, and this is probably important seeing as you are running your site from a virtual machine, when you run the site with python manage.py runserver, run it like this...
python manage.py runserver virtual.server.ip.address:8000
Obviously replace 'virtual.server.ip.address' with that virtual machines actual ip address.
I print *DEBUG = None* and my django works.

Accessing Django Admin over HTTPS behind Nginx

I've got django running in uwsgi behind nginx. When I try to access https://site/admin/ I get the expected login screen. Logging in via the form seems to succeed, however, I simply end up back at the login screen. Firebug shows a redirect to the plain http://site/admin/ url which is then redirectec by nginx to the https url.
Help! I'm confused as to how to force the admin app to use only https urls.
Note this seems to be a related, unanswered question: https://example.com/admin redirects to https://admin in Django Nginx and gunicorn
Adding the following to nginx.conf fixed the issue for me.
location / {
...
include uwsgi_params;
uwsgi_param HTTP_X_FORWARDED_PROTOCOL https;
uwsgi_param UWSGI_SCHEME $scheme;
}
Along with adding the following to settings.py:
SESSION_COOKIE_SECURE = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')
CSRF_COOKIE_SECURE = True
the following should be all you need to have all traffic to the admin app redirected to
https
location /site/admin/ {
rewrite ^ https://$host/$request_uri permanent;
}
If that doesn't work, can you post your actual nginx config bits? Can't really suggest more then that without your actual config to look at.
Update for Django 1.8 settings.py:
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_REDIRECT_EXEMPT = [r'^(?!admin/).*']
And for your developement rig you may want to overwrite SECURE_SSL_REDIRECT = False in your local settings.