Skip to content

Commit 81fa4b4

Browse files
craigdstomchristie
authored andcommitted
Fix CSRF cookie check failure when using session auth with django 1.11.6+ (#6113)
Test included. Fixes #6088
1 parent 2fab783 commit 81fa4b4

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

rest_framework/authentication.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,10 @@ def enforce_csrf(self, request):
135135
"""
136136
Enforce CSRF validation for session based authentication.
137137
"""
138-
reason = CSRFCheck().process_view(request, None, (), {})
138+
check = CSRFCheck()
139+
# populates request.META['CSRF_COOKIE'], which is used in process_view()
140+
check.process_request(request)
141+
reason = check.process_view(request, None, (), {})
139142
if reason:
140143
# CSRF failed, bail with explicit error message
141144
raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)

tests/test_authentication.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import base64
66

77
import pytest
8+
from django.conf import settings
89
from django.conf.urls import include, url
910
from django.contrib.auth.models import User
1011
from django.db import models
@@ -202,6 +203,26 @@ def test_post_form_session_auth_failing_csrf(self):
202203
response = self.csrf_client.post('/session/', {'example': 'example'})
203204
assert response.status_code == status.HTTP_403_FORBIDDEN
204205

206+
def test_post_form_session_auth_passing_csrf(self):
207+
"""
208+
Ensure POSTing form over session authentication with CSRF token succeeds.
209+
Regression test for #6088
210+
"""
211+
from django.middleware.csrf import _get_new_csrf_token
212+
213+
self.csrf_client.login(username=self.username, password=self.password)
214+
215+
# Set the csrf_token cookie so that CsrfViewMiddleware._get_token() works
216+
token = _get_new_csrf_token()
217+
self.csrf_client.cookies[settings.CSRF_COOKIE_NAME] = token
218+
219+
# Post the token matching the cookie value
220+
response = self.csrf_client.post('/session/', {
221+
'example': 'example',
222+
'csrfmiddlewaretoken': token,
223+
})
224+
assert response.status_code == status.HTTP_200_OK
225+
205226
def test_post_form_session_auth_passing(self):
206227
"""
207228
Ensure POSTing form over session authentication with logged in

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy