Search code examples
tornadocsrf

How can I use the xsrf_cookies setting in tornado at ease?


Good afternoon, everyone~

As we know, when I add the xsrf_cookies = True in the settings of tornado,I should use xsrf_form_html() in the template, also , should do something if I choose sending message by ajax.

But,what should I do or set the tornado ,when I want have both the xsrf_cookies and not xsrf_cookies. En,it means,I want it could check the xsrf and could not check the xsrf by my thought.Maybe I could not explain it clearly?

For example,in Django,we can use @csrf_exempt not check csrf when we add the check-xsrf to middleware.

Hope I explained it enough~

Now, I want anyone can tell me: 1,Did here any way like the example in tornado?If has,told me please~ 2,If not ,what should I do, if I must add the 'check' and 'not check' together?


Solution

  • http://tornado-zh.readthedocs.io/zh/latest/guide/security.html

    In the end of the page,it shows the RequestHandler.check_xsrf_cookie().

    En,it is the chinese version.

    It shows,I can overide the check_xsrf_cookie like below:

    def check_xsrf_cookie(self):
        pass
    

    En,throuth the source:

    def check_xsrf_cookie(self):
        token = (self.get_argument("_xsrf", None) or
                 self.request.headers.get("X-Xsrftoken") or
                 self.request.headers.get("X-Csrftoken"))
        if not token:
            raise HTTPError(403, "'_xsrf' argument missing from POST")
        _, token, _ = self._decode_xsrf_token(token)
        _, expected_token, _ = self._get_raw_xsrf_token()
        if not token:
            raise HTTPError(403, "'_xsrf' argument has invalid format")
        if not _time_independent_equals(utf8(token), utf8(expected_token)):
            raise HTTPError(403, "XSRF cookie does not match POST argument")
    

    It seems to be :

    check the xsrf ,raise error or return None.

    So, overide pass maybe enough.