成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

去掉django rest framework強(qiáng)制的csrf檢查

amc / 758人閱讀

摘要:近期的項目,前端的是在上跑的,然后向我們后端的開發(fā)服務(wù)器進(jìn)行請求。那怎么去掉這個功能呢,我們現(xiàn)在就是要進(jìn)行跨域請求。這里里面有就直接進(jìn)入了,沒有下面的檢查了。所以我們只要自己給添加一個這樣的屬性就好了。最直接的方法還是去寫一個啊,哈哈。

近期的項目,前端的js是在localhost上跑的,然后向我們后端的開發(fā)服務(wù)器進(jìn)行請求。但是突然前端說所有的post請求都報csrf校驗錯誤了,甚是奇怪,之前為了開發(fā)方便已經(jīng)把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)

原來是這樣,最近給系統(tǒng)增加了用戶登陸功能,使用的就是SessionAuthorization和TokenAuthorization,然后在SessionAuthorization中調(diào)用了self.enforce_csrf(request)而這個調(diào)用的又是上面的CSRFCheck,這個類是重載了django里面的csrf middleware,而且沒發(fā)現(xiàn)有地方可以關(guān)掉這個功能,即使在django里面去掉這個middleware,但是這個還是會調(diào)用的。

那怎么去掉這個功能呢,我們現(xiàn)在就是要進(jìn)行跨域請求。

最簡單了,直接注釋掉上面的self.enforce_csrf(request)這一行代碼就行了或者在設(shè)置中添加一項,比如改成

GLOBAL_CSRF_CHECK = True
if GLOBAL_CSRF_CHECK:
    self.enforce_csrf(request)

我們繼續(xù)看源代碼,到middleware的代碼里面去。

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

里面主要有兩個函數(shù),一個是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會在請求到達(dá)view函數(shù)之前被調(diào)用,可以理解為一個過濾器吧。

 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就直接進(jìn)入view了,沒有下面的檢查了。所以我們只要自己給request添加一個這樣的屬性就好了。最直接的方法還是去寫一個middleware啊,哈哈。

代碼很簡單

class DisableCSRFCheck(object):
    def process_request(self, request):
        setattr(request, "_dont_enforce_csrf_checks", True)

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/37459.html

相關(guān)文章

  • Django前后端分離實踐

    摘要:更新嘗試了一下實現(xiàn)前后端分離,新的文章如下前后端分離之初試更新可另外用實現(xiàn)前后端分離,這篇文章可能局限性太大,只是個人的入門實踐剛剛學(xué)習(xí)前端快一年,后臺方面了解甚少,于是決定踩踩坑,學(xué)習(xí)一下。 2018.9.6更新:嘗試了一下REST framework實現(xiàn)前后端分離,新的文章如下Django前后端分離之REST framework初試 2018.8.27更新:可另外用 restful...

    Mike617 評論0 收藏0
  • Django REST FrameWork中文教程3:基于類視圖

    摘要:看起來不錯再次,它現(xiàn)在仍然非常類似于基于功能的視圖。我們還需要重構(gòu)一下我們使用基于類的視圖。中文文檔目錄中文教程序列化中文教程請求和響應(yīng)中文教程基于類的視圖中文教程驗證和權(quán)限中文教程關(guān)系和超鏈接中文教程中文教程模式和客戶端庫 我們也可以使用基于類的視圖編寫我們的API視圖,而不是基于函數(shù)的視圖。我們將看到這是一個強(qiáng)大的模式,允許我們重用常用功能,并幫助我們保持代碼DRY。 使用基于類的...

    UnixAgain 評論0 收藏0
  • Django REST FrameWork中文教程3:基于類視圖

    摘要:看起來不錯再次,它現(xiàn)在仍然非常類似于基于功能的視圖。我們還需要重構(gòu)一下我們使用基于類的視圖。中文文檔目錄中文教程序列化中文教程請求和響應(yīng)中文教程基于類的視圖中文教程驗證和權(quán)限中文教程關(guān)系和超鏈接中文教程中文教程模式和客戶端庫 我們也可以使用基于類的視圖編寫我們的API視圖,而不是基于函數(shù)的視圖。我們將看到這是一個強(qiáng)大的模式,允許我們重用常用功能,并幫助我們保持代碼DRY。 使用基于類的...

    shiguibiao 評論0 收藏0
  • Django REST FrameWork中文教程3:基于類視圖

    摘要:看起來不錯再次,它現(xiàn)在仍然非常類似于基于功能的視圖。我們還需要重構(gòu)一下我們使用基于類的視圖。中文文檔目錄中文教程序列化中文教程請求和響應(yīng)中文教程基于類的視圖中文教程驗證和權(quán)限中文教程關(guān)系和超鏈接中文教程中文教程模式和客戶端庫 我們也可以使用基于類的視圖編寫我們的API視圖,而不是基于函數(shù)的視圖。我們將看到這是一個強(qiáng)大的模式,允許我們重用常用功能,并幫助我們保持代碼DRY。 使用基于類的...

    canopus4u 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<