I am newbie in Django and try to implement 'autologout' using a tierce app django-session-timeout
It works but I would like to improve behavior
the session expire after time set in settings.py but there is no refresh so that it is disconnect and redirect to login page except if user click elsewhere
in other word, the user is disconnect (as user session expire) but not automatically redirect to login page -> need a user event
is it possible to improve this without writing my own middleware?
settings.py
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',
'django_session_timeout.middleware.SessionTimeoutMiddleware',
]
LOGIN_URL = 'home'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
SESSION_EXPIRE_SECONDS = 900 # 900 - >15 minutes = 15 * 60
SESSION_EXPIRE_AFTER_LAST_ACTIVITY = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True
Related
I'm trying to use an iframe of my django site in a different domain, however whenever I submit a form, It says the CSRF cookies is not set. This occurs in chrome and safari. I am running Django 3.1.0.
I've tried adding the following settings in my settings.py:
SESSION_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SECURE = True
X_FRAME_OPTIONS = 'ALLOWALL'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_SAMESITE = None
CSRF_COOKIE_HTTPONLY = False
CSRF_TRUSTED_ORIGINS = [
'otherdomain.com',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
]
Further, I can confirm the csrf token is being set in the form using:
{% csrf_token %}
Lastly, I've also added the #xframe_options_exempt decorator to the form page.
Edit: I am also using the render method to display the form as recommended by the documentation.
Edit2: For some more context, this form functions fine when it is used in the host domain (not an iframe)
Unfortunately the csrf exempt decorator is not an option for me. I've tried clearing my cookies, though it does not solve my problem. Any help would be greatly appreciated!
This was solved by changing the value of CSRF_COOKIE_SAMESITE to 'None' instead of None. Apparently Chrome requires it to be an explicit string, not an empty value
I am trying to implement the single sign-on using Angular, Django, IIS server.
In IIS windows authentication is enabled.
Angular intercepter code :
intercept(req: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {
console.log("in intercept")
req = req.clone({
withCredentials: true });
return next.handle(req); }
Django settings.py:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',]
AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.RemoteUserBackend',)
CORS_ORIGIN_ALLOW_ALL = True
ALLOWED_HOSTS = ["*"]
Getting error:
(IP-address) has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Try this configuration in settings.py
CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_CREDENTIALS = True # This one is required when you are using withCredentials: true
The problem will lie in the Django setup, please have a look at this link: https://stackoverflow.com/a/38162454/4587598
If at first try won't work, strip all settings.py and setup from scratch, firstly checking if CORS issue does not occur and afterwards add authentication complexity.
try django-cors-headers
pip install django-cors-headers
And set it up
In your settings.py
INSTALLED_APPS = (
...
'corsheaders',
...
)
You will also need to add a middleware class to listen in on responses:
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
CorsMiddleware should be placed as high as possible, especially before any middleware that can generate responses such as Django's CommonMiddleware
CORS_ORIGIN_ALLOW_ALL = True
I am using django 1.8 along with mongoengine and a custom Middleware that is supposed to add a user and a toked to a django request.
These two are passed in the header of the request.
The middleware class is the following :
from models import MongoToken
class TokenAuthenticationMiddleware(object):
def process_request(self, request):
if "HTTP_AUTHORIZATION" not in request.META:
return
tokenkey = get_authorization_header(request).split()[1]
token = MongoToken.objects.get(key=tokenkey)
user = User.objects.get(username=request.META.get("HTTP_USERNAME"))
if token.key == tokenkey and token.user.is_active:
request.user = user
request.token = tokenkey
I also put this in my MIDDLEWARE_CLASSES block of the settings.py files:
MIDDLEWARE_CLASSES = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'myproject.middleware.MongoAuthenticationMiddleware',
'myproject.middleware.TokenAuthenticationMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
And when the considered view is reached, my token is here because thanks to the header params but the user is Null.
Then I am wondering if I did something wrong with this because it does not work.
Thank you for your help.
Alex.
I read Django tutorial but found nothing related to never expiring session.
Requirement - User should logged out only if he/she initiate by clicking on logout.
How can I solve this issue?
My django project settings related to session -
INSTALLED_APPS = (
..
'django.contrib.sessions',
..
)
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
#'rest_framework.authentication.SessionAuthentication',
)
}
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
)
By default Django keeps sessions between browser closes. You can modify this behavior with the SESSION_EXPIRE_AT_BROWSER_CLOSE setting.
https://docs.djangoproject.com/en/1.8/topics/http/sessions/#browser-length-vs-persistent-sessions
I'd like to add simple cache functionality to my site. I have enabled cache for anonymous users, but it does not work as expected. I'm using memcached.
settings.py
########################### caching #################################
CACHE_PORT = '11211'
CACHE_MIDDLEWARE_SECONDS = 60
CACHE_MIDDLEWARE_KEY_PREFIX = "default"
CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True
# Production Environment
if ON_OPENSHIFT:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '%s:%s' % (os.environ['OPENSHIFT_INTERNAL_IP'], CACHE_PORT),
}
}
CACHE_VIEW_LENGTH = datetime.now() + timedelta(30) # 30 day cache expiration
# Development Environment
else:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:%s' % CACHE_PORT,
}
}
CACHE_VIEW_LENGTH = datetime.now() + timedelta(1) # Set to 0 for development
MIDDLEWARE_CLASSES = (
#cache - must be first in middleware_classes
'django.middleware.cache.UpdateCacheMiddleware',
#cache end
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
'django.middleware.clickjacking.XFrameOptionsMiddleware',
#cache - must be last in middleware_classes
'django.middleware.cache.FetchFromCacheMiddleware',
#cache end
)
Since I have set CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True, I would except that if I load page as logged in user, I would not get cached version.
I loaded index page where is list of my objects. There are 10 objects. I added new object through form. When I checked on my index page again, I see only 10 objects.
So my question is simple: Why is django ignoring my setting for anonymous only and caches pages for logged in users?
CACHE_MIDDLEWARE_ANONYMOUS_ONLY option was removed in Django 1.8. Here is the ticket about that: https://code.djangoproject.com/ticket/15201
When CACHE_MIDDLEWARE_ANONYMOUS_ONLY was working, it was only about writing to cache. When CACHE_MIDDLEWARE_ANONYMOUS_ONLY is True, non-anonymous request never writes to cache, but reads from cache.