Django + Django REST csrf on AJAX site requests

I have a web application with django that has a module that uses the django-rest-framework to provide the API used by the mobile application .

If I enter the web application , csrf tokens in the mobile application throw me 403 - Forbiden with the following answer

  {"detail":"CSRF Failed: CSRF token missing or incorrect."} 

When I exit the web application , I can use the mobile application again (even without a login again, from the first session).

I have the following about django-rest-framework-jwt

 CORS_ORIGIN_ALLOW_ALL = True CORS_URLS_REGEX = r'^/api/v1/.*$' CORS_ALLOW_CREDENTIALS = True JWT_AUTH = { 'JWT_SECRET_KEY': SECRET_KEY, 'JWT_ALGORITHM': 'HS256', 'JWT_VERIFY': True, 'JWT_VERIFY_EXPIRATION': True, 'JWT_LEEWAY': 0, 'JWT_EXPIRATION_DELTA': timedelta(days=120), 'JWT_AUDIENCE': None, 'JWT_ISSUER': None, 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': timedelta(days=7), 'JWT_AUTH_HEADER_PREFIX': 'JWT', } REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',) } 

And finally here INSTALLED_APPS

 INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: 'django.contrib.admindocs', 'djangotoolbox', 'autoload', 'dbindexer', 'gaeblob_storage', ################################## WEB APP MODULES 'myapp.modulos.presentacion', 'myapp.modulos.principal', 'myapp.modulos.proyecto', 'myapp.modulos.estado_1', 'myapp.modulos.estado_2', 'myapp.modulos.estado_3', 'myapp.modulos.comunicacion', ################################## API MODULE 'myapp.modulos.api', 'django_forms_bootstrap', # API Rest 'jwt', 'rest_framework', 'rest_framework_jwt', 'corsheaders', 'django_filters', # djangoappengine should come last, so it can override a few manage.py commands 'djangoappengine', ) 

There is also a login window,

 def login_view(request): status = "" if request.user.is_authenticated(): return redirect('/principal') #Cambiar cuando este el estado disponible else: if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None and user.is_active: login(request, user) FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY,request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: status = "Usuario y/o Password incorrecto" form = LoginForm() ctx = {'form':form, 'status': status} return render(request,'presentacion/login.html',ctx) return render(request,'presentacion/login.html') 
+5
source share
2 answers

“By default, the user is sent a“ Forbidden response 403 ”if the incoming request does not perform the checks performed by CsrfViewMiddleware. This should usually be seen only if the cross-site requests were correctly selected or when, due to a programming error, the CSRF token was not enabled since POST form . " https://docs.djangoproject.com/en/1.8/ref/csrf/#rejected-requests

You need to include the csrf token in the form data along with the request.

You can get it from cookies or from the DOM if CSRF_COOKIE_HTTPONLY = True.

See the Django AJAX docs for more details.

0
source

JSONWebTokenAuthentication your DEFAULT_AUTHENTICATION_CLASSES to have a JSONWebTokenAuthentication first.

If you provide a valid JWT for your API, the request must be authenticated without validating a valid session containing the CSRF token.

0
source

All Articles