search
HomeBackend DevelopmentPython TutorialAn introduction to Tornado's method of preventing cross-site attacks in Python

This article brings you an introduction to Tornado’s method of preventing cross-site attacks in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Cross-site request forgery (CSRF or XSRF) is a malicious use of a website. Through CSRF, attackers can assume the user's identity and perform malicious operations without the user's knowledge.

1. CSRF attack principle

The following figure shows the basic principle of CSRF. Site1 is a website with CSRF vulnerabilities, and SIte2 is a malicious website with attacks.

An introduction to Tornados method of preventing cross-site attacks in Python
The content of the above picture is analyzed as follows:

  • The user first visited Site1, a website with CSRF vulnerabilities, successfully logged in and obtained cookies. After that, all The user's visit to Site1 will carry Site1's cookie, so it is considered a valid operation by Site1.

  • At this time, the user visited Site2, a site with offensive behavior, and the return page of Site2 contained a link to access Site1 for malicious operations, but it was disguised as legitimate content. , for example, the following hyperlink looks like a lottery information, but it actually wants to submit a withdrawal request to the Site1 site

<a>
三百万元抽奖,免费拿
</a>
  • Once the user clicks on the malicious link, A request was sent to the Site1 site without your knowledge. Because the user has logged in to Site1 before and has not logged out, when Site1 receives the user's request and the accompanying cookie, it will consider the request to be a normal request sent by the user. At this point, the purpose of the malicious site has been achieved.

2. Use Tornado to prevent CSRF attacks

In order to prevent CSRF attacks, each request is required to include a parameter value as the matching storage of the token The corresponding value in the cookie.

Tornado applications can provide tokens to the page through a Cookie header and a hidden HTML form element. This way, when the form for a legitimate page is submitted, it will include the form values ​​and the stored cookies. If the two match, the Tornado application approval request is valid.

Enabling Tornado’s CSRF prevention function requires two steps.

[1] Pass in the xsrf_cookies=True parameter when instantiating tornado.web.Application, that is:

application=tornado.web.Application([
(r'/',MainHandler),
],
cookie_secret='DONT_LEAK_SECRET',
xsrf_cookies=True,
)

or:

settings={
"cookie_secret":"DONT_LEAK_SECRET",
"xsrf_cookies":True
}

application=tornado.web.Application([
(r'/',MainHandler),
],**settings)

When tornado.web.Application needs When there are too many initialized parameters, you can pass in named parameters in the form of a setting dictionary like this example

[2] In each template file with HTML expression, add xsrf_form_html() function tags to all forms. For example:


{% module xsrf_form_html() %}

The {% module xsrf_form_html() %} here plays the role of adding hidden elements to the form to prevent cross-site requests.

Tornado's secure cookie support and XSRF prevention framework reduce a lot of burdens on application developers. Without them, developers need to think about many detailed prevention measures, so Tornado's built-in security features are also very useful.

The above is the detailed content of An introduction to Tornado's method of preventing cross-site attacks in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault思否. If there is any infringement, please contact admin@php.cn delete
For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

Python: Is it Truly Interpreted? Debunking the MythsPython: Is it Truly Interpreted? Debunking the MythsMay 12, 2025 am 12:05 AM

Pythonisnotpurelyinterpreted;itusesahybridapproachofbytecodecompilationandruntimeinterpretation.1)Pythoncompilessourcecodeintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).2)Thisprocessallowsforrapiddevelopmentbutcanimpactperformance,req

Python concatenate lists with same elementPython concatenate lists with same elementMay 11, 2025 am 12:08 AM

ToconcatenatelistsinPythonwiththesameelements,use:1)the operatortokeepduplicates,2)asettoremoveduplicates,or3)listcomprehensionforcontroloverduplicates,eachmethodhasdifferentperformanceandorderimplications.

Interpreted vs Compiled Languages: Python's PlaceInterpreted vs Compiled Languages: Python's PlaceMay 11, 2025 am 12:07 AM

Pythonisaninterpretedlanguage,offeringeaseofuseandflexibilitybutfacingperformancelimitationsincriticalapplications.1)InterpretedlanguageslikePythonexecuteline-by-line,allowingimmediatefeedbackandrapidprototyping.2)CompiledlanguageslikeC/C transformt

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.