Are we still need CSRF cookie in Django when SAMESITE enable? - python

There is the samesite cooike that can protect user from CSRF attack. so are we still need enable the Django's django.middleware.csrf.CsrfViewMiddleware or we can safely disable it now?

Related

How to fetch a csrftoken from a django server?

I'm reconfiguring my CDN and I want to begin caching pages that use csrf tokens for form submission. Currently, I'm submitting the csrf token with javascript in a post request with:
axios.defaults.headers.post['X-CSRFToken'] = getCookie('csrftoken')
This works pretty well locally and allowed me to remove the csrf tokens from the templates.
This obviously will not work if I'm accessing cached pages from the CDN. So is it possible for me to fetch a csrf token from the server using Axios and subsequently set it in a post request? If so how do I do this?
An alternative approach would be to disable csrf which I tried already but I couldn't fully disable it. If you are signed into admin csrf protection is automatically enabled even on your frontend forms, I couldn't figure out how to remove this not sure if it's a wagtail or django thing.
I'm using Django 2.2 + Wagtail 2.11.

How to include Django CSRF token in request through ngrok?

I am building a Django app that will be hosted on a local network and perform authentication using Facebook Login. Since Facebook Login requires the callback address for a login to either be localhost or publicly-addressable, I'm using ngrok to create an address for Facebook to return data to.
After the user logs in with Facebook, I perform a POST with AJAX from the template with their data to a local view (/fb_login) which saves to my database in Django. Since authentication is based on this database, I don't think it's wise to avoid the CSRF checks Django performs on this view.
To include the CSRF token in the POST to /fb_login, I'm using the following which a few forums suggested:
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
This should only include the CSRF token to relative URLs (which I understand to be the best practice). When I run the server on localhost and perform the Facebook Login from the same machine, this works fine. However, when I run the system on localhost and access it through ngrok from another machine on the local network and perform the Facebook Login, I get a 403 and a message saying the CSRF check failed. This leads me to believe that the ngrok URL isn't considered "local", so the CSRF token isn't being set.
Assuming I know what my ngrok URL is at the time my Django server starts, can I include it in what's considered a "local" address for the purposes of including the CSRF token? Is there another way to do this securely? As a note, web development is not my area, so please let me know if I'm misunderstanding something here. Thanks!

Django_hosts Not Working With Django's Default Authentication

I'm using this package called django_hosts to re-route urls for some apps.
Everything is working fine except for the fact that django_hosts is not working with Django Authentication.
I hosted this url api.example.com, so on this page with the url api.example.com:8000/add_post, I want users to add post but before doing that you must be authenticated. So after I logged in, I still can't submit post via the form talkless of posting. But when I go back to example.com, it shows that I'm logged in but api.example.com is telling me otherwise.
How do I make django authentication work with this package?
The problem is that the authentication token is hooked to the domain. Using Django's default configuration, the api.example.com can't access the example.com auth token.
You can change this behaviour by setting the SESSION_COOKIE_DOMAIN configuration in your settings.py module:
SESSION_COOKIE_DOMAIN = 'example.com'
But not too fast! Do it carefully, otherwise you can break your application:
Be cautious when updating this setting on a production site. If you
update this setting to enable cross-domain cookies on a site that
previously used standard domain cookies, existing user cookies will be
set to the old domain. This may result in them being unable to log in
as long as these cookies persist.
More info on the official documentation.

django admin returns 403 csrf error

I am producing a django/angular project. Django being the backend administration and Angular being the frontend/public display. I have created a Django 1.11 app and loaded all files, installed dependencies, etc. Locally, the site works fine and as expected. Also, since forms will be Angular js I commented out the django.middleware.csrf.CsrfViewMiddleware in my settings.py which I thought would disable the csrf token even being needed, but apparently not.
After setting up server and installing files the admin login page appears but I get the following error when I try and login:
Forbidden (CSRF token missing or incorrect.): /admin/login/
Any ideas on why this is happening would be greatly appreciated.
You can't commented out the 'django.middleware.csrf.CsrfViewMiddleware' in your settings.py, The CSRF middleware provides easy-to-use protection against Cross Site Request Forgeries. Since you are using Augualr js instead of django forms and views, you can set the csrftoken cookie in your browser cookies. Check this for detail: https://docs.djangoproject.com/en/1.11/ref/csrf/#module-django.middleware.csrf

Django API Post method returns 403 error

I am trying to setup the Django API (a POST API endpoint). I want to have the same URL path pointing to the same function that handle differently due to if it is POST or GET. Thus, I used the method like this
def handle_post(request):
dict = {}
dict['email'] = "test"
if request.method == "POST":
return HttpResponse(json.dumps(dict), content_type="application/json")
In the url.py, I have the following code
router = routers.DefaultRouter()
router.register(r'notes', UsernotesViewSet)
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^admin/', include(admin_site.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^docs/', include('rest_framework_swagger.urls')),
url(r'^example/postrequest', handle_post),
)
But I can not get this work when I perform POST onto the URL http://127.0.0.1:8000/example/postrequest?requestid=abc&starthour=10. I did not post anything, but just change the method to POST from GET on httpclient to try this API. Is it ok if I did not post any content to URL ?
I am getting the 403 error, as below :
Forbidden (403)
CSRF verification failed. Request aborted.
You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.
If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests.
Appreciated any help.
I could not understand your question correctly, but CSRF verification failure is caused when "requests via ‘unsafe’ methods, such as POST, PUT and DELETE" are performed without using recommended defense settings against CSRF (Cross Site Request Forgeries).
You can read more on this link.
There is a quick work-around to problem. You can use csrf_exempt decorator to mark a view as being exempt from the protection ensured by the CSRF View Middleware (django.middleware.csrf.CsrfViewMiddleware). Example:
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
#csrf_exempt
def my_view(request):
return HttpResponse('Hello world')
You can read more about is here.
Have a read of the Django docs on CSRF protection. If your api is going to be accessed by javascript in the browser, then there are instructions for how to include the token in an ajax request.
If the API is accessed in a different way e.g. from a mobile client that doesn't use cookies, then it might be appropriate to turn off the CSRF protection for that view, using the csrf_exempt decorator.
Forbidden (403)
CSRF verification failed. Request aborted.
You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.
If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests.
More information is available with DEBUG=True.

Categories

Resources