Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I use django_comments as comment system of my site, but when I post the comment, it gives 403 error. Why?
This is my settings:
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',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
The others forms works well. They won't give 403 error.
Your other forms work because you have disabled the CSRF middleware. This is a bad idea, because it makes your website vulnerable to a CSRF attack.
The post_comment view from django_comments explicitly uses the csrf_protect decorator. Therefore, you must include {% csrf_token %} in the form tag in your template to prevent CSRF errors.
If you still have problems, then it is probably the view. As the docs say, you must make sure that the template is rendered with the request object, otherwise the {% csrf_token %} tag will not work.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 days ago.
This post was edited and submitted for review 7 days ago.
Improve this question
I am currently looking for a way to manage the Django cache from the administration (having the possibility to turn it off, turn it on, or leave it on with a timeout of 8 hours).
I have tried to use for this the django cache framework, with 3 buttons in the administration to different functions that turn off, activate or modify the cache timeout with no results (the cache remains activated with no possibility to turn it off or modify its timeout).
I tried to use a script that restarts the server once one of these options is chosen, but it doesn't work as it should (this must happen because I can't dynamically modify the settings.py file).
First I create two buttons in the admin panel
<a href="/caching/turn_on_cache/">
<button class="btn btn-success">Turn on cache for 8 hours</button>
</a>
<a href="/caching/turn_off_cache/">
<button class="btn btn-danger">Turn off cache</button>
</a>
Then, I add the two views for set up cache
from django.shortcuts import redirect
from django.core.cache import cache
from django.contrib import messages
import logging
logger = logging.getLogger(__name__)
def turn_on_cache(request):
cache.set('cache', True, 60*60*8)
logging.info(cache.get('cache')) ->>> This return True
messages.success(request, "Cache turned on for 8 hours")
return redirect('admin:index')
def turn_off_cache(request):
cache.set('cache', False, 60*60*8)
logging.info(cache.get('cache')) ->>> This return false
messages.success(request, "Cache turned off")
return redirect('admin:index')
But when I see the django-debug-toolbar the system keeps making sql queries
my settings.py
DEBUG = True
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
#'waffle.middleware.WaffleMiddleware',
"debug_toolbar.middleware.DebugToolbarMiddleware",
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'my_cache_table',
'TIMEOUT': 604800 # 7 days
}
}
CACHE_MIDDLEWARE_ALIAS = 'default'
CACHE_MIDDLEWARE_SECONDS = 60
CACHE_MIDDLEWARE_KEY_PREFIX = ''
Any different approach to this problem?
Thanks in advance
when I try to login using a browser it works correctly but, when I try to user Postman to post username & password it throws csrf token error.
urlpatterns = [
path('', include('rest_framework.urls')),
.......
]
Middlewares
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.middleware.csrf.CsrfViewMiddleware',
]
When I access the api from a browser is allows me to log in.
Currently not using any Permission classes and authentication_classes.
but tested with rest_framework_simplejwt.authentication.JWTAuthentication at the begining.
Currently not using any.
By default, Django needs the crsf_token in all the submitted forms to any views to ensure that the request comes from a legitimate place, so there are several questions here:
1) Why it works from the browser?
Probably, this is because you have a line {% csrf_token %} in your template.html after the <form> tag. This is the way to say to django that it must include a cookie called 'csrf_token' when returning the rendered template. So, when the form is submitted, it takes the cookie 'csrf_token' and includes it in the POST request. When the request is in the server side, django checks that the csrf_token is in the request header and allows the request to continue normally.
This is done automatically and you don't need to care about it only if you include the line {% csrf_token %} after the <form> tag.
2) Why it does not work from postman?
When you send a post from postman, you're not sending the csrf_token in the requests header but you only send the {'username': 'user', 'password': 'pass'} and django rejects the requests since it has no way to know that the request come from a trustworthy place.
3) How can you make the login work from postman?
I see 2 options here.
You can first execute a GET to the login template from postman, and you will see that it returns a cookie called csrf_token. Then you can copy that cookie to include it in your request header. (You can configure postman to save the cookie headers and use them in future requests)
You can use the decorator #csrf_exempt in your view to say django not to check the csrf_token for any view. Here is more info about it https://docs.djangoproject.com/en/3.1/ref/csrf/
But I would not recommend do this in a login view since it could cause that any login request will be accepted regardless of its origin, causing strongly insecure platforms.
I am working on a dJango web and follow the tutorial to protect it against CSRF, I did something and not sure is it write now install or not, how can I see or check it?
From the docs, to enable CSRF protection for your views, follow these steps:
Add the middleware 'django.middleware.csrf.CsrfViewMiddleware' to your list of middleware classes, MIDDLEWARE_CLASSES in your settings.py. (It should come before any view middleware that assume that CSRF attacks have been dealt with.)
In any template that uses a POST form, use the csrf_token tag inside the element if the form is for an internal URL, e.g.:
<form action="." method="post">{% csrf_token %}
In the corresponding view functions, ensure that the 'django.core.context_processors.csrf' context processor is being used.
Following these steps will check that CSRF tokens are included properly.
By default, a ‘403 Forbidden’ response is sent to the user if an incoming request fails the checks performed by CsrfViewMiddleware. This should usually only be seen when there is a genuine Cross Site Request Forgery, or when, due to a programming error, the CSRF token has not been included with a POST form.
See the Docs for more info.
Check the MIDDLEWARE_CLASSES tuple in settings.py contains this
'django.middleware.csrf.CsrfViewMiddleware',
If this is there in the tuple , then csrf is installed.
Some like this:
MIDDLEWARE_CLASSES = (
'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',
)
I have been trying to set up CSRF protection on my POST forms on my django 1.4.3 site and have been getting the 403 CSRF cookie not set error.
I believe I have followed the doc in detail, followed advice on many forums but all to no avail. I have stripped back the code as much as possible and the cookie just does not set. The csrfmiddlewaretoken is present, so that's not the source of the problem. I'm at my wit's end. No doubt the answer is stupidly simple, I just need a fresh set of eyes to point it out to me...
So here's some code:
#urls.py
...
url(r'^csrf/$', csrf_test, name='csrf_test'),
...
#views.py
...
from django.views.decorators.csrf import csrf_protect
#csrf_protect
def csrf_test(request):
c = {}
c.update(csrf(request))
return render_to_response('csrf.html', c)
...
<!-- csrf.html -->
<html>
<body>
<form action="" method="post">
{% csrf_token %}
<input name="Submit" value="Submit" type="submit"/>
</form>
</body>
</html>
#settings.py
...
MIDDLEWARE_CLASSES = (
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
#for db transactions. Check middleware order if faulty
'django.middleware.transaction.TransactionMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
...
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
'django.core.context_processors.csrf',
'django.core.context_processors.request',
)
...
I am running the django development server on 127.0.0.1:8000.
I have cookies enabled on my browsers and have confirmed cookies are being set from other websites.
I have checked the csrfmiddlewaretoken is being passed as a POST variable.
I always get the error, this is not intermittent.
I have no problem with POST forms when I have disabled the middleware/used #csrf_exempt.
As I say, I'm at my wit's end. What on earth have I missed?
Thanks
Nathan
EDIT:
It now works, but I have no idea what has changed. For anyone reading this in the future I created a new project and app, it created the cookie straight away. Thinking it must have been a settings issue I changed the order of my MIDDLEWARE_CLASSES entries by moving 'django.middleware.csrf.CsrfViewMiddleware' down below 'django.contrib.sessions.middleware.SessionMiddleware'. I ran the original app and it worked. However to test whether the settings change was responsible I reversed the change. It still worked. Go figure.
I hope this helps someone in the future FWIW.
Nathan
if you're using render_to_response then you should probably use a RequestContext
This will handle the csrf protection for you -
def csrf_test(request):
render_to_response('csrf.html', context_instance=RequestContext(request))
You don't need to include the csrf_protect decorator, since you've got the csrf middleware.
def csrf_test(request):
.....
return render(request, 'csrf.html', { ..... })
I have a weird issue when I try to save a new user through the admin interface.
I get a 403 HTTP status code error.
I've changed nothing in the auth application.
Here are my middlewares:
MIDDLEWARE_CLASSES = (
'johnny.middleware.LocalStoreClearMiddleware',
'johnny.middleware.QueryCacheMiddleware',
#'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
#'django.middleware.cache.FetchFromCacheMiddleware',
)
I've no idea where to look, or either have any idea of what could provocate this. Any clue is welcome.
Your user probably has not permissions to add new users. It's a normal behaviour to return 403 code in this case. View the doc, please: https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.decorators.permission_required.
And (in this case) your user can have permission to delete users because it's the decoupled permissions.
You can view permissions of the user it: http://yoursite.com/admin/auth/user/{user_id}/ ( from superuser or user that can view permissions of other users).
Update. The author of the question found the decision: the situation was because of Apache settings (switching mod_security off fixed the problem). Unfortunately I have not deep knowledge about the module and I can't give more detailed information.