Skip to content

Commit

Permalink
Fix CSRF cookie check failure when using session auth with django 1.1…
Browse files Browse the repository at this point in the history
…1.6+ (#6113)

Test included. Fixes #6088
  • Loading branch information
craigds authored and tomchristie committed Aug 7, 2018
1 parent 2fab783 commit 81fa4b4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
5 changes: 4 additions & 1 deletion rest_framework/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,10 @@ def enforce_csrf(self, request):
"""
Enforce CSRF validation for session based authentication.
"""
reason = CSRFCheck().process_view(request, None, (), {})
check = CSRFCheck()
# populates request.META['CSRF_COOKIE'], which is used in process_view()
check.process_request(request)
reason = check.process_view(request, None, (), {})
if reason:
# CSRF failed, bail with explicit error message
raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)
Expand Down
21 changes: 21 additions & 0 deletions tests/test_authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import base64

import pytest
from django.conf import settings
from django.conf.urls import include, url
from django.contrib.auth.models import User
from django.db import models
Expand Down Expand Up @@ -202,6 +203,26 @@ def test_post_form_session_auth_failing_csrf(self):
response = self.csrf_client.post('/session/', {'example': 'example'})
assert response.status_code == status.HTTP_403_FORBIDDEN

def test_post_form_session_auth_passing_csrf(self):
"""
Ensure POSTing form over session authentication with CSRF token succeeds.
Regression test for #6088
"""
from django.middleware.csrf import _get_new_csrf_token

self.csrf_client.login(username=self.username, password=self.password)

# Set the csrf_token cookie so that CsrfViewMiddleware._get_token() works
token = _get_new_csrf_token()
self.csrf_client.cookies[settings.CSRF_COOKIE_NAME] = token

# Post the token matching the cookie value
response = self.csrf_client.post('/session/', {
'example': 'example',
'csrfmiddlewaretoken': token,
})
assert response.status_code == status.HTTP_200_OK

def test_post_form_session_auth_passing(self):
"""
Ensure POSTing form over session authentication with logged in
Expand Down

0 comments on commit 81fa4b4

Please sign in to comment.