近期的项目,前端的js是在localhost上跑的,而后向咱们后端的开发服务器进行请求。可是忽然前端说全部的post请求都报csrf校验错误了,甚是奇怪,以前为了开发方便已经把django的csrf middleware注释掉了啊,为何还会错误,因为返回值格式仍是django rest的通用格式,确定问题是出在这里面,因而翻了一下它的源代码看了看。前端
from django.middleware.csrf import CsrfViewMiddleware class CSRFCheck(CsrfViewMiddleware): def _reject(self, request, reason): # Return the failure reason instead of an HttpResponse return reason class SessionAuthentication(BaseAuthentication): """ Use Django's session framework for authentication. """ def authenticate(self, request): """ Returns a `User` if the request session currently has a logged in user. Otherwise returns `None`. """ # Get the underlying HttpRequest object request = request._request user = getattr(request, 'user', None) # Unauthenticated, CSRF validation not required if not user or not user.is_active: return None self.enforce_csrf(request) # CSRF passed with authenticated user return (user, None) def enforce_csrf(self, request): """ Enforce CSRF validation for session based authentication. """ reason = CSRFCheck().process_view(request, None, (), {}) if reason: # CSRF failed, bail with explicit error message raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)
原来是这样,最近给系统增长了用户登录功能,使用的就是SessionAuthorization和TokenAuthorization,而后在SessionAuthorization中调用了self.enforce_csrf(request)
而这个调用的又是上面的CSRFCheck
,这个类是重载了django里面的csrf middleware,并且没发现有地方能够关掉这个功能,即便在django里面去掉这个middleware,可是这个仍是会调用的。django
那怎么去掉这个功能呢,咱们如今就是要进行跨域请求。后端
self.enforce_csrf(request)
这一行代码就好了或者在设置中添加一项,好比改为GLOBAL_CSRF_CHECK = True if GLOBAL_CSRF_CHECK: self.enforce_csrf(request)
class CsrfViewMiddleware(object): """ Middleware that requires a present and correct csrfmiddlewaretoken for POST requests that have a CSRF cookie, and sets an outgoing CSRF cookie. This middleware should be used in conjunction with the csrf_token template tag. """ # The _accept and _reject methods currently only exist for the sake of the # requires_csrf_token decorator. def _accept(self, request): # Avoid checking the request twice by adding a custom attribute to # request. This will be relevant when both decorator and middleware # are used. request.csrf_processing_done = True return None def _reject(self, request, reason): logger.warning('Forbidden (%s): %s', reason, request.path, extra={ 'status_code': 403, 'request': request, } ) return _get_failure_view()(request, reason=reason) def process_view(self, request, callback, callback_args, callback_kwargs): if getattr(request, 'csrf_processing_done', False): return None try: csrf_token = _sanitize_token( request.COOKIES[settings.CSRF_COOKIE_NAME]) # Use same token next time request.META['CSRF_COOKIE'] = csrf_token except KeyError: csrf_token = None # Generate token and store it in the request, so it's # available to the view. request.META["CSRF_COOKIE"] = _get_new_csrf_key() # Wait until request.META["CSRF_COOKIE"] has been manipulated before # bailing out, so that get_token still works if getattr(callback, 'csrf_exempt', False): return None # Assume that anything not defined as 'safe' by RFC2616 needs protection if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'): if getattr(request, '_dont_enforce_csrf_checks', False): # Mechanism to turn off CSRF checks for test suite. # It comes after the creation of CSRF cookies, so that # everything else continues to work exactly the same # (e.g. cookies are sent, etc.), but before any # branches that call reject(). return self._accept(request) if request.is_secure(): # Suppose user visits http://example.com/ # An active network attacker (man-in-the-middle, MITM) sends a # POST form that targets https://example.com/detonate-bomb/ and # submits it via JavaScript. # # The attacker will need to provide a CSRF cookie and token, but # that's no problem for a MITM and the session-independent # nonce we're using. So the MITM can circumvent the CSRF # protection. This is true for any HTTP connection, but anyone # using HTTPS expects better! For this reason, for # https://example.com/ we need additional protection that treats # http://example.com/ as completely untrusted. Under HTTPS, # Barth et al. found that the Referer header is missing for # same-domain requests in only about 0.2% of cases or less, so # we can use strict Referer checking. referer = request.META.get('HTTP_REFERER') if referer is None: return self._reject(request, REASON_NO_REFERER) # Note that request.get_host() includes the port. good_referer = 'https://%s/' % request.get_host() if not same_origin(referer, good_referer): reason = REASON_BAD_REFERER % (referer, good_referer) return self._reject(request, reason) if csrf_token is None: # No CSRF cookie. For POST requests, we insist on a CSRF cookie, # and in this way we can avoid all CSRF attacks, including login # CSRF. return self._reject(request, REASON_NO_CSRF_COOKIE) # Check non-cookie token for match. request_csrf_token = "" if request.method == "POST": request_csrf_token = request.POST.get('csrfmiddlewaretoken', '') if request_csrf_token == "": # Fall back to X-CSRFToken, to make things easier for AJAX, # and possible for PUT/DELETE. request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '') if not constant_time_compare(request_csrf_token, csrf_token): return self._reject(request, REASON_BAD_TOKEN) return self._accept(request) def process_response(self, request, response): if getattr(response, 'csrf_processing_done', False): return response # If CSRF_COOKIE is unset, then CsrfViewMiddleware.process_view was # never called, probaby because a request middleware returned a response # (for example, contrib.auth redirecting to a login page). if request.META.get("CSRF_COOKIE") is None: return response if not request.META.get("CSRF_COOKIE_USED", False): return response # Set the CSRF cookie even if it's already set, so we renew # the expiry timer. response.set_cookie(settings.CSRF_COOKIE_NAME, request.META["CSRF_COOKIE"], max_age = 60 * 60 * 24 * 7 * 52, domain=settings.CSRF_COOKIE_DOMAIN, path=settings.CSRF_COOKIE_PATH, secure=settings.CSRF_COOKIE_SECURE, httponly=settings.CSRF_COOKIE_HTTPONLY ) # Content varies with the CSRF cookie, so set the Vary header. patch_vary_headers(response, ('Cookie',)) response.csrf_processing_done = True return response
里面主要有两个函数,一个是process view,另外一个是process response。这里就不得不说django middleware的工做原理了。跨域
https://docs.djangoproject.com/en/1.6/topics/http/middleware/服务器
process_request() is called on each request, before Django decides which view to execute. process_view() is called just before Django calls the view. process_response() is called on all responses before they’re returned to the browser.
因此这个middleware的process view会在请求到达view函数以前被调用,能够理解为一个过滤器吧。cookie
if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'): if getattr(request, '_dont_enforce_csrf_checks', False): return self._accept(request)
这里request里面有_dont_enforce_csrf_checks
就直接进入view了,没有下面的检查了。因此咱们只要本身给request添加一个这样的属性就行了。最直接的方法仍是去写一个middleware啊,哈哈。session
代码很简单less
class DisableCSRFCheck(object): def process_request(self, request): setattr(request, '_dont_enforce_csrf_checks', True)