{"id":75873,"date":"2020-01-20T12:25:03","date_gmt":"2020-01-20T06:55:03","guid":{"rendered":"https:\/\/www.vskills.in\/certification\/tutorial\/?p=75873"},"modified":"2024-04-12T14:17:41","modified_gmt":"2024-04-12T08:47:41","slug":"csrf-protection-2","status":"publish","type":"page","link":"https:\/\/www.vskills.in\/certification\/tutorial\/csrf-protection-2\/","title":{"rendered":"CSRF Protection"},"content":{"rendered":"<p>The django.contrib.csrf package protects against Cross-Site Request Forgery (CSRF). CSRF, also known as \u201csession riding,\u201d is a Web site security exploit. It happens when a malicious Web site tricks a user into unknowingly loading a URL from a site at which that user is already authenticated, hence taking advantage of the user\u2019s authenticated status. This can be a bit tricky to understand at first, so we walk through two examples in this section.<\/p>\n<p><strong>A Simple CSRF Example<\/strong> &#8211; Suppose you\u2019re logged in to a webmail account at example.com. This webmail site has a Log Out button that points to the URL example.com\/logout \u2014 that is, the only action you need to take in order to log out is to visit the page example.com\/logout. A malicious site can coerce you to visit the URL example.com\/logout by including that URL as a hidden &lt;iframe&gt; on its own (malicious) page. Thus, if you\u2019re logged in to the example.com webmail account and visit the malicious page that has an &lt;iframe&gt; to example.com\/logout, the act of visiting the malicious page will log you out from example.com.<\/p>\n<p>Clearly, being logged out of a webmail site against your will is not a terrifying breach of security, but<\/p>\n<p>this same type of exploit can happen to <em>any<\/em> site that \u201ctrusts\u201d users, such as an online banking site or an e-commerce site.<\/p>\n<p><strong>A More Complex CSRF Example<\/strong> &#8211; In the previous example, example.com was partially at fault because it allowed a state change (i.e., logging the user out) to be requested via the HTTP GET method. It\u2019s much better practice to require an HTTP POST for any request that changes state on the server. But even Web sites that require POST for state-changing actions are vulnerable to CSRF.<\/p>\n<p>Suppose example.com has upgraded its Log Out functionality so that it\u2019s a &lt;form&gt; button that is requested via POST to the URL example.com\/logout. Furthermore, the logout &lt;form&gt; includes this hidden field:<\/p>\n<p>&lt;input type=&#8221;hidden&#8221; name=&#8221;confirm&#8221; value=&#8221;true&#8221; \/&gt;<\/p>\n<p>This ensures that a simple POST to the URL example.com\/logout won\u2019t log a user out; in order for a user to log out, the user must request example.com\/logout via POST <em>and<\/em> send the confirm POST variable with a value of &#8216;true&#8217;. Well, despite the extra security, this arrangement can still be exploited by CSRF \u2014 the malicious page just needs to do a little more work. Attackers can create an entire form targeting your site, hide it in an invisible &lt;iframe&gt;, and then use JavaScript to submit that form automatically.<\/p>\n<p><strong>Preventing CSRF<\/strong> &#8211; How, then, can your site protect itself from this exploit? The first step is to make sure all GET requests are free of side effects. That way, if a malicious site includes one of your pages as an &lt;iframe&gt;, it won\u2019t have a negative effect.<\/p>\n<p>That leaves POST requests. The second step is to give each POST &lt;form&gt; a hidden field whose value is secret and is generated from the user\u2019s session ID. Then, when processing the form on the server side, check for that secret field and raise an error if it doesn\u2019t validate. This is exactly what Django\u2019s CSRF prevention layer does, as explained in the sections that follow.<\/p>\n<p><u>Using the CSRF Middleware<\/u> &#8211; The django.contrib.csrf package contains only one module: middleware.py. This module contains a Django middleware class, CsrfMiddleware, which implements the CSRF protection.<\/p>\n<p>To activate this CSRF protection, add &#8216;django.contrib.csrf.middleware.CsrfMiddleware&#8217; to the MIDDLEWARE_CLASSES setting in your settings file. This middleware needs to process the response <em>after<\/em> SessionMiddleware, so CsrfMiddleware must appear <em>before<\/em> SessionMiddleware in the list (because the response middleware is processed last-to-first). Also, it must process the response before the response gets compressed or otherwise mangled, so CsrfMiddleware must come after GZipMiddleware. Once you\u2019ve added that to your MIDDLEWARE_CLASSES setting, you\u2019re done. See the section \u201cOrder of MIDDLEWARE_CLASSES\u201d in Chapter 13 for more explanation. In case you\u2019re interested, here\u2019s how CsrfMiddleware works. It does these two things:<\/p>\n<ul>\n<li>It modifies outgoing requests by adding a hidden form field to all POST forms, with the name csrfmiddlewaretoken and a value that is a hash of the session ID plus a secret key. The middleware does <em>not<\/em> modify the response if there\u2019s no session ID set, so the performance penalty is negligible for requests that don\u2019t use sessions.<\/li>\n<li>On all incoming POST requests that have the session cookie set, it checks that csrfmiddlewaretoken is present and correct. If it isn\u2019t, the user will get a 403 HTTP The content of the 403 error page is the message \u201cCross Site Request Forgery detected. Request aborted.\u201d<\/li>\n<\/ul>\n<p>This ensures that only forms originating from your Web site can be used to POST data back. This middleware deliberately targets only HTTP POST requests (and the corresponding POST forms). As we explained, GET requests ought never to have side effects; it\u2019s your own responsibility to ensure this.<\/p>\n<p>POST requests not accompanied by a session cookie are not protected, but they don\u2019t <em>need<\/em> to be protected, because a malicious Web site could make these kind of requests anyway. To avoid altering non-HTML requests, the middleware checks the response\u2019s Content-Type header before modifying it. Only pages that are served as text\/html or application\/xml+xhtml are modified.<\/p>\n<p><u>Limitations of the CSRF Middleware<\/u> &#8211; CsrfMiddleware requires Django\u2019s session framework to work. (See Chapter 12 for more on sessions.) If you\u2019re using a custom session or authentication framework that manually manages session cookies, this middleware will not help you. If your application creates HTML pages and forms in some unusual way (e.g., if it sends fragments of HTML in JavaScript document.write statements), you might bypass the filter that adds the hidden field to the form. In this case, the form submission will always fail. (This happens because CsrfMiddleware uses a regular expression to add the csrfmiddlewaretoken field to your HTML before the page is sent to the client, and the regular expression sometimes cannot handle wacky HTML.) If you suspect this might be happening, just view the source in your Web browser to see whether csrfmiddlewaretoken was inserted into your &lt;form&gt;.<\/p>\n\n\n<p><a href=\"https:\/\/www.vskills.in\/certification\/tutorial\/certified-django-developer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Back to Tutorial<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The django.contrib.csrf package protects against Cross-Site Request Forgery (CSRF). CSRF, also known as \u201csession riding,\u201d is a Web site security exploit. It happens when a malicious Web site tricks a user into unknowingly loading a URL from a site at which that user is already authenticated, hence taking advantage of the user\u2019s authenticated status. This&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"categories":[8655],"tags":[2654],"class_list":["post-75873","page","type-page","status-publish","hentry","category-django-web-development","tag-csrf-protection"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>CSRF Protection - Tutorial<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.vskills.in\/certification\/tutorial\/csrf-protection-2\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"CSRF Protection - Tutorial\" \/>\n<meta property=\"og:description\" content=\"The django.contrib.csrf package protects against Cross-Site Request Forgery (CSRF). CSRF, also known as \u201csession riding,\u201d is a Web site security exploit. It happens when a malicious Web site tricks a user into unknowingly loading a URL from a site at which that user is already authenticated, hence taking advantage of the user\u2019s authenticated status. This...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.vskills.in\/certification\/tutorial\/csrf-protection-2\/\" \/>\n<meta property=\"og:site_name\" content=\"Tutorial\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/vskills.in\/\" \/>\n<meta property=\"article:modified_time\" content=\"2024-04-12T08:47:41+00:00\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/csrf-protection-2\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/csrf-protection-2\/\",\"name\":\"CSRF Protection - Tutorial\",\"isPartOf\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\"},\"datePublished\":\"2020-01-20T06:55:03+00:00\",\"dateModified\":\"2024-04-12T08:47:41+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/csrf-protection-2\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.vskills.in\/certification\/tutorial\/csrf-protection-2\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/csrf-protection-2\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"CSRF Protection\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"name\":\"Tutorial\",\"description\":\"Vskills - A initiative in elearning and certification\",\"publisher\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\",\"name\":\"Vskills\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"contentUrl\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"width\":73,\"height\":55,\"caption\":\"Vskills\"},\"image\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/vskills.in\/\",\"https:\/\/x.com\/vskills_in\",\"https:\/\/www.linkedin.com\/company-beta\/1371554\/\",\"https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"CSRF Protection - Tutorial","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.vskills.in\/certification\/tutorial\/csrf-protection-2\/","og_locale":"en_US","og_type":"article","og_title":"CSRF Protection - Tutorial","og_description":"The django.contrib.csrf package protects against Cross-Site Request Forgery (CSRF). CSRF, also known as \u201csession riding,\u201d is a Web site security exploit. It happens when a malicious Web site tricks a user into unknowingly loading a URL from a site at which that user is already authenticated, hence taking advantage of the user\u2019s authenticated status. This...","og_url":"https:\/\/www.vskills.in\/certification\/tutorial\/csrf-protection-2\/","og_site_name":"Tutorial","article_publisher":"https:\/\/www.facebook.com\/vskills.in\/","article_modified_time":"2024-04-12T08:47:41+00:00","twitter_misc":{"Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/csrf-protection-2\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/csrf-protection-2\/","name":"CSRF Protection - Tutorial","isPartOf":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website"},"datePublished":"2020-01-20T06:55:03+00:00","dateModified":"2024-04-12T08:47:41+00:00","breadcrumb":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/csrf-protection-2\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.vskills.in\/certification\/tutorial\/csrf-protection-2\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/csrf-protection-2\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.vskills.in\/certification\/tutorial\/"},{"@type":"ListItem","position":2,"name":"CSRF Protection"}]},{"@type":"WebSite","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","name":"Tutorial","description":"Vskills - A initiative in elearning and certification","publisher":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization","name":"Vskills","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","contentUrl":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","width":73,"height":55,"caption":"Vskills"},"image":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/vskills.in\/","https:\/\/x.com\/vskills_in","https:\/\/www.linkedin.com\/company-beta\/1371554\/","https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw"]}]}},"_links":{"self":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75873","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/comments?post=75873"}],"version-history":[{"count":4,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75873\/revisions"}],"predecessor-version":[{"id":83407,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75873\/revisions\/83407"}],"wp:attachment":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/media?parent=75873"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/categories?post=75873"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/tags?post=75873"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}