In openedx I have used Xblock.json_handler for third party api consumption . But I want to disable csrf authentication for that one post api , can anyone help me out with that ?
1 Answers
They are many ways to do just that. But just have in mind that you cannot disable CSRF at global level unless you will like to create your own custom middleware. see documentation
1.) using csrf_exempt method
If you want some views not to use CSRF, you can use @csrf_exempt. Add @csrf_exempt to every view that you want to disable
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def my_view(request):
return 'CSRF is disabled for this view'
2.) Using setting.py configurations
In setting.py in MIDDLEWARE you can simply remove/comment this line of code:
'django.middleware.csrf.CsrfViewMiddleware',
Just remember that SessionAuthentication performs its own CSRF validation. and this will trigger CSRF missing error if commented while using sessionAuthentication..
3.) Creating your own Custom Middleware
To disable CSRF in Global, you can write a custom middleware, like this
from django.utils.deprecation import MiddlewareMixin
class DisableCsrfCheck(MiddlewareMixin):
def process_request(self, req):
attr = '_dont_enforce_csrf_checks'
if not getattr(req, attr, False):
setattr(req, attr, True)
then add this class
yourApp_name.middlewarefilename.DisableCsrfCheck
to
MIDDLEWARE_CLASSES lists
,
before
django.middleware.csrf.CsrfViewMiddleware

- 2,322
- 2
- 21
- 38