(self, request)
| 347 | return f"CSRF token from {token_source} {reason}." |
| 348 | |
| 349 | def _check_token(self, request): |
| 350 | # Access csrf_secret via self._get_secret() as rotate_token() may have |
| 351 | # been called by an authentication middleware during the |
| 352 | # process_request() phase. |
| 353 | try: |
| 354 | csrf_secret = self._get_secret(request) |
| 355 | except InvalidTokenFormat as exc: |
| 356 | raise RejectRequest(f"CSRF cookie {exc.reason}.") |
| 357 | |
| 358 | if csrf_secret is None: |
| 359 | # No CSRF cookie. For POST requests, we insist on a CSRF cookie, |
| 360 | # and in this way we can avoid all CSRF attacks, including login |
| 361 | # CSRF. |
| 362 | raise RejectRequest(REASON_NO_CSRF_COOKIE) |
| 363 | |
| 364 | # Check non-cookie token for match. |
| 365 | request_csrf_token = "" |
| 366 | if request.method == "POST": |
| 367 | try: |
| 368 | request_csrf_token = request.POST.get("csrfmiddlewaretoken", "") |
| 369 | except UnreadablePostError: |
| 370 | # Handle a broken connection before we've completed reading the |
| 371 | # POST data. process_view shouldn't raise any exceptions, so |
| 372 | # we'll ignore and serve the user a 403 (assuming they're still |
| 373 | # listening, which they probably aren't because of the error). |
| 374 | pass |
| 375 | |
| 376 | if request_csrf_token == "": |
| 377 | # Fall back to X-CSRFToken, to make things easier for AJAX, and |
| 378 | # possible for PUT/DELETE. |
| 379 | try: |
| 380 | # This can have length CSRF_SECRET_LENGTH or CSRF_TOKEN_LENGTH, |
| 381 | # depending on whether the client obtained the token from |
| 382 | # the DOM or the cookie (and if the cookie, whether the cookie |
| 383 | # was masked or unmasked). |
| 384 | request_csrf_token = request.META[settings.CSRF_HEADER_NAME] |
| 385 | except KeyError: |
| 386 | raise RejectRequest(REASON_CSRF_TOKEN_MISSING) |
| 387 | token_source = settings.CSRF_HEADER_NAME |
| 388 | else: |
| 389 | token_source = "POST" |
| 390 | |
| 391 | try: |
| 392 | _check_token_format(request_csrf_token) |
| 393 | except InvalidTokenFormat as exc: |
| 394 | reason = self._bad_token_message(exc.reason, token_source) |
| 395 | raise RejectRequest(reason) |
| 396 | |
| 397 | if not _does_token_match(request_csrf_token, csrf_secret): |
| 398 | reason = self._bad_token_message("incorrect", token_source) |
| 399 | raise RejectRequest(reason) |
| 400 | |
| 401 | def process_request(self, request): |
| 402 | try: |
no test coverage detected