{"title":"クロスサイトリクエストフォージェリ (CSRF) 対策","version":"2.1","locale":"ja","docname":"ref/csrf","url":"/ja/2.1/ref/csrf/","canonical":"https://djangodocs.dev/ja/2.1/ref/csrf/","summary":"CSRF ミドルウェアとテンプレートタグは、簡単に扱える Cross Site Request Forgeries 対策を提供しています。このタイプの攻撃は、訪問者のログイン情報を悪用してあなたのサイトに何らかの操作を行うことを目的とした、リンクやフォームボタン、 JavaScript…","html":"<span id=\"cross-site-request-forgery-protection\"></span><h1>クロスサイトリクエストフォージェリ (CSRF) 対策<a class=\"heading-anchor\" href=\"#module-django.middleware.csrf\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<p>CSRF ミドルウェアとテンプレートタグは、簡単に扱える <a class=\"reference external\" href=\"https://www.squarefree.com/securitytips/web-developers.html#CSRF\">Cross Site Request Forgeries</a> 対策を提供しています。このタイプの攻撃は、訪問者のログイン情報を悪用してあなたのサイトに何らかの操作を行うことを目的とした、リンクやフォームボタン、 JavaScript を設置した悪意のあるウェブサイトによって行われます。また、関連する攻撃として、ユーザーを騙して別のユーザー権限でログインさせる 'ログイン CSRF' と呼ばれる攻撃もありますが、これも対策に含まれます。</p>\n<p>CSRF 攻撃に対する第一の防御は、 GET リクエスト (および <span class=\"target\" id=\"index-4\"></span><a class=\"rfc reference external\" href=\"https://datatracker.ietf.org/doc/html/rfc7231.html#section-4.2.1\"><strong>RFC 7231 Section 4.2.1</strong></a> で定義された ‘安全な’ メソッド) から副作用を取り除くというものです。そして、 POST、PUT、DELETE のような、’安全でない’ メソッ ドによるリクエストについては、下記の手順に従うことで対策することができます。</p>\n<section id=\"how-to-use-it\">\n<span id=\"using-csrf\"></span><h2>使用方法<a class=\"heading-anchor\" href=\"#how-to-use-it\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>CSRF 対策をあなたのビューで有効にするには、以下の手順に従ってください:</p>\n<ol class=\"arabic\">\n<li><p>CSRF ミドルウェアは、デフォルトで <a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-MIDDLEWARE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">MIDDLEWARE</span></code></a> 設定で有効になっています。もし設定をオーバーライドするときは、<code class=\"docutils literal notranslate\"><span class=\"pre\">'django.middleware.csrf.CsrfViewMiddleware'</span></code> が、 CSRF 攻撃への対策がされていることを前提とした他の全てのビュー・ミドルウェアの前に来るようにしてください。</p>\n<p>(推奨されませんが) もし対策を無効にする場合は、<a class=\"reference internal\" href=\"#django.views.decorators.csrf.csrf_protect\" title=\"django.views.decorators.csrf.csrf_protect\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">csrf_protect()</span></code></a> を使って特定のビューを保護することができます. (下記をご覧ください)</p>\n</li>\n<li><p>POST フォームを使う全てのテンプレートで、POST が内部 URL に使われる場合は、<code class=\"docutils literal notranslate\"><span class=\"pre\">&lt;form&gt;</span></code> 要素の内部で <a class=\"reference internal\" href=\"/ja/2.1/ref/templates/builtins/#std-templatetag-csrf_token\"><code class=\"xref std std-ttag docutils literal notranslate\"><span class=\"pre\">csrf_token</span></code></a> タグを使用してください。</p>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Django template code\"><code><span class=\"p\">&lt;</span><span class=\"nt\">form</span> <span class=\"na\">method</span><span class=\"o\">=</span><span class=\"s\">&quot;post&quot;</span><span class=\"p\">&gt;</span><span class=\"cp\">{%</span> <span class=\"k\">csrf_token</span> <span class=\"cp\">%}</span>\n</code></pre></div>\n<p>この方法は、外部の URL を対象にする POST フォームで使ってはなりません。CSRF トークンが外部に漏れ、脆弱性の原因となります。</p>\n</li>\n<li><p>一致するビュー機能の中で、<code class=\"docutils literal notranslate\"><span class=\"pre\">{%</span> <span class=\"pre\">csrf_token</span> <span class=\"pre\">%}</span></code> が適切に動作するように、<a class=\"reference internal\" href=\"/ja/2.1/ref/templates/api/#django.template.RequestContext\" title=\"django.template.RequestContext\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RequestContext</span></code></a> がレスポンスをレンダリングするようにしてください。<a class=\"reference internal\" href=\"/ja/2.1/topics/http/shortcuts/#django.shortcuts.render\" title=\"django.shortcuts.render\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">render()</span></code></a> 、汎用ビューもしくは contrib アプリケーションを使う場合は、これら全て <code class=\"docutils literal notranslate\"><span class=\"pre\">RequestContext</span></code> を使用するためすでに CSRF 対策はなされています。</p></li>\n</ol>\n<section id=\"ajax\">\n<span id=\"csrf-ajax\"></span><h3>AJAX<a class=\"heading-anchor\" href=\"#ajax\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>While the above method can be used for AJAX POST requests, it has some\ninconveniences: you have to remember to pass the CSRF token in as POST data with\nevery POST request. For this reason, there is an alternative method: on each\nXMLHttpRequest, set a custom <code class=\"docutils literal notranslate\"><span class=\"pre\">X-CSRFToken</span></code> header (as specified by the\n<a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_HEADER_NAME\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_HEADER_NAME</span></code></a> setting) to the value of the CSRF token. This is\noften easier because many JavaScript frameworks provide hooks that allow\nheaders to be set on every request.</p>\n<p>First, you must get the CSRF token. How to do that depends on whether or not\nthe <a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_USE_SESSIONS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_USE_SESSIONS</span></code></a> and <a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_COOKIE_HTTPONLY\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_HTTPONLY</span></code></a> settings\nare enabled.</p>\n<section id=\"acquiring-the-token-if-csrf-use-sessions-and-csrf-cookie-httponly-are-false\">\n<span id=\"acquiring-csrf-token-from-cookie\"></span><h4>Acquiring the token if <a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_USE_SESSIONS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_USE_SESSIONS</span></code></a> and <a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_COOKIE_HTTPONLY\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_HTTPONLY</span></code></a> are <code class=\"docutils literal notranslate\"><span class=\"pre\">False</span></code><a class=\"heading-anchor\" href=\"#acquiring-the-token-if-csrf-use-sessions-and-csrf-cookie-httponly-are-false\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>The recommended source for the token is the <code class=\"docutils literal notranslate\"><span class=\"pre\">csrftoken</span></code> cookie, which will be\nset if you've enabled CSRF protection for your views as outlined above.</p>\n<p>デフォルトでは、CSRF トークンの cookie は <code class=\"docutils literal notranslate\"><span class=\"pre\">csrftoken</span></code> という名前ですが、<a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_COOKIE_NAME\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_NAME</span></code></a> の設定を通じて変更することができます。</p>\n<p>トークンを取得するのは簡単です:</p>\n<div class=\"code-block\" data-language=\"javascript\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">JavaScript</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"JavaScript code\"><code><span class=\"c1\">// using jQuery</span>\n<span class=\"kd\">function</span><span class=\"w\"> </span><span class=\"nx\">getCookie</span><span class=\"p\">(</span><span class=\"nx\">name</span><span class=\"p\">)</span><span class=\"w\"> </span><span class=\"p\">{</span>\n<span class=\"w\">    </span><span class=\"kd\">var</span><span class=\"w\"> </span><span class=\"nx\">cookieValue</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"kc\">null</span><span class=\"p\">;</span>\n<span class=\"w\">    </span><span class=\"k\">if</span><span class=\"w\"> </span><span class=\"p\">(</span><span class=\"nb\">document</span><span class=\"p\">.</span><span class=\"nx\">cookie</span><span class=\"w\"> </span><span class=\"o\">&amp;&amp;</span><span class=\"w\"> </span><span class=\"nb\">document</span><span class=\"p\">.</span><span class=\"nx\">cookie</span><span class=\"w\"> </span><span class=\"o\">!==</span><span class=\"w\"> </span><span class=\"s1\">&#39;&#39;</span><span class=\"p\">)</span><span class=\"w\"> </span><span class=\"p\">{</span>\n<span class=\"w\">        </span><span class=\"kd\">var</span><span class=\"w\"> </span><span class=\"nx\">cookies</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"nb\">document</span><span class=\"p\">.</span><span class=\"nx\">cookie</span><span class=\"p\">.</span><span class=\"nx\">split</span><span class=\"p\">(</span><span class=\"s1\">&#39;;&#39;</span><span class=\"p\">);</span>\n<span class=\"w\">        </span><span class=\"k\">for</span><span class=\"w\"> </span><span class=\"p\">(</span><span class=\"kd\">var</span><span class=\"w\"> </span><span class=\"nx\">i</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"mf\">0</span><span class=\"p\">;</span><span class=\"w\"> </span><span class=\"nx\">i</span><span class=\"w\"> </span><span class=\"o\">&lt;</span><span class=\"w\"> </span><span class=\"nx\">cookies</span><span class=\"p\">.</span><span class=\"nx\">length</span><span class=\"p\">;</span><span class=\"w\"> </span><span class=\"nx\">i</span><span class=\"o\">++</span><span class=\"p\">)</span><span class=\"w\"> </span><span class=\"p\">{</span>\n<span class=\"w\">            </span><span class=\"kd\">var</span><span class=\"w\"> </span><span class=\"nx\">cookie</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"nx\">jQuery</span><span class=\"p\">.</span><span class=\"nx\">trim</span><span class=\"p\">(</span><span class=\"nx\">cookies</span><span class=\"p\">[</span><span class=\"nx\">i</span><span class=\"p\">]);</span>\n<span class=\"w\">            </span><span class=\"c1\">// Does this cookie string begin with the name we want?</span>\n<span class=\"w\">            </span><span class=\"k\">if</span><span class=\"w\"> </span><span class=\"p\">(</span><span class=\"nx\">cookie</span><span class=\"p\">.</span><span class=\"nx\">substring</span><span class=\"p\">(</span><span class=\"mf\">0</span><span class=\"p\">,</span><span class=\"w\"> </span><span class=\"nx\">name</span><span class=\"p\">.</span><span class=\"nx\">length</span><span class=\"w\"> </span><span class=\"o\">+</span><span class=\"w\"> </span><span class=\"mf\">1</span><span class=\"p\">)</span><span class=\"w\"> </span><span class=\"o\">===</span><span class=\"w\"> </span><span class=\"p\">(</span><span class=\"nx\">name</span><span class=\"w\"> </span><span class=\"o\">+</span><span class=\"w\"> </span><span class=\"s1\">&#39;=&#39;</span><span class=\"p\">))</span><span class=\"w\"> </span><span class=\"p\">{</span>\n<span class=\"w\">                </span><span class=\"nx\">cookieValue</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"nb\">decodeURIComponent</span><span class=\"p\">(</span><span class=\"nx\">cookie</span><span class=\"p\">.</span><span class=\"nx\">substring</span><span class=\"p\">(</span><span class=\"nx\">name</span><span class=\"p\">.</span><span class=\"nx\">length</span><span class=\"w\"> </span><span class=\"o\">+</span><span class=\"w\"> </span><span class=\"mf\">1</span><span class=\"p\">));</span>\n<span class=\"w\">                </span><span class=\"k\">break</span><span class=\"p\">;</span>\n<span class=\"w\">            </span><span class=\"p\">}</span>\n<span class=\"w\">        </span><span class=\"p\">}</span>\n<span class=\"w\">    </span><span class=\"p\">}</span>\n<span class=\"w\">    </span><span class=\"k\">return</span><span class=\"w\"> </span><span class=\"nx\">cookieValue</span><span class=\"p\">;</span>\n<span class=\"p\">}</span>\n<span class=\"kd\">var</span><span class=\"w\"> </span><span class=\"nx\">csrftoken</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"nx\">getCookie</span><span class=\"p\">(</span><span class=\"s1\">&#39;csrftoken&#39;</span><span class=\"p\">);</span>\n</code></pre></div>\n<p>上記のコードは <a class=\"reference external\" href=\"https://github.com/js-cookie/js-cookie/\">JavaScript Cookie library</a> を使って <code class=\"docutils literal notranslate\"><span class=\"pre\">getCookie</span></code> を置き換えればシンプルにできます:</p>\n<div class=\"code-block\" data-language=\"javascript\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">JavaScript</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"JavaScript code\"><code><span class=\"kd\">var</span><span class=\"w\"> </span><span class=\"nx\">csrftoken</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"nx\">Cookies</span><span class=\"p\">.</span><span class=\"nx\">get</span><span class=\"p\">(</span><span class=\"s1\">&#39;csrftoken&#39;</span><span class=\"p\">);</span>\n</code></pre></div>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">注釈</p>\n<p>CSRF トークンは、DOM の中でも提供されますが、それはテンプレート内で明示的に <a class=\"reference internal\" href=\"/ja/2.1/ref/templates/builtins/#std-templatetag-csrf_token\"><code class=\"xref std std-ttag docutils literal notranslate\"><span class=\"pre\">csrf_token</span></code></a> を使ったときに限ります。cookie は標準のトークンを含んでいます; <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code> は DOM 内のトークンよりも cookie を優先します。いずれにせよ、トークンが DOM 内で提供されているときも cookie は使えるので、cookie を使うようにしてください！</p>\n</aside>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">警告</p>\n<p>ビューが <a class=\"reference internal\" href=\"/ja/2.1/ref/templates/builtins/#std-templatetag-csrf_token\"><code class=\"xref std std-ttag docutils literal notranslate\"><span class=\"pre\">csrf_token</span></code></a> テンプレートタグを含むテンプレートをレンダリングしていない場合、Django は CSRF トークンクッキーをセットしない可能性があります。フォームがページに動的に追加される場合がその典型です。このケースに対応するため、Django はクッキーを強制的にセットするビューのデコレータを提供しています: <a class=\"reference internal\" href=\"#django.views.decorators.csrf.ensure_csrf_cookie\" title=\"django.views.decorators.csrf.ensure_csrf_cookie\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">ensure_csrf_cookie()</span></code></a>。</p>\n</aside>\n</section>\n<section id=\"acquiring-the-token-if-csrf-use-sessions-or-csrf-cookie-httponly-is-true\">\n<span id=\"acquiring-csrf-token-from-html\"></span><h4>Acquiring the token if <a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_USE_SESSIONS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_USE_SESSIONS</span></code></a> or <a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_COOKIE_HTTPONLY\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_HTTPONLY</span></code></a> is <code class=\"docutils literal notranslate\"><span class=\"pre\">True</span></code><a class=\"heading-anchor\" href=\"#acquiring-the-token-if-csrf-use-sessions-or-csrf-cookie-httponly-is-true\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>If you activate <a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_USE_SESSIONS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_USE_SESSIONS</span></code></a> or\n<a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_COOKIE_HTTPONLY\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_HTTPONLY</span></code></a>, you must include the CSRF token in your HTML\nand read the token from the DOM with JavaScript:</p>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Django template code\"><code><span class=\"cp\">{%</span> <span class=\"k\">csrf_token</span> <span class=\"cp\">%}</span>\n<span class=\"p\">&lt;</span><span class=\"nt\">script</span> <span class=\"na\">type</span><span class=\"o\">=</span><span class=\"s\">&quot;text/javascript&quot;</span><span class=\"p\">&gt;</span>\n<span class=\"c1\">// using jQuery</span>\n<span class=\"kd\">var</span><span class=\"w\"> </span><span class=\"nx\">csrftoken</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"nx\">jQuery</span><span class=\"p\">(</span><span class=\"s2\">&quot;[name=csrfmiddlewaretoken]&quot;</span><span class=\"p\">).</span><span class=\"nx\">val</span><span class=\"p\">();</span>\n<span class=\"p\">&lt;/</span><span class=\"nt\">script</span><span class=\"p\">&gt;</span>\n</code></pre></div>\n</section>\n<section id=\"setting-the-token-on-the-ajax-request\">\n<h4>Setting the token on the AJAX request<a class=\"heading-anchor\" href=\"#setting-the-token-on-the-ajax-request\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>Finally, you'll have to actually set the header on your AJAX request, while\nprotecting the CSRF token from being sent to other domains using\n<a class=\"reference external\" href=\"https://api.jquery.com/jQuery.ajax/\">settings.crossDomain</a> in jQuery 1.5.1\nand newer:</p>\n<div class=\"code-block\" data-language=\"javascript\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">JavaScript</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"JavaScript code\"><code><span class=\"kd\">function</span><span class=\"w\"> </span><span class=\"nx\">csrfSafeMethod</span><span class=\"p\">(</span><span class=\"nx\">method</span><span class=\"p\">)</span><span class=\"w\"> </span><span class=\"p\">{</span>\n<span class=\"w\">    </span><span class=\"c1\">// these HTTP methods do not require CSRF protection</span>\n<span class=\"w\">    </span><span class=\"k\">return</span><span class=\"w\"> </span><span class=\"p\">(</span><span class=\"sr\">/^(GET|HEAD|OPTIONS|TRACE)$/</span><span class=\"p\">.</span><span class=\"nx\">test</span><span class=\"p\">(</span><span class=\"nx\">method</span><span class=\"p\">));</span>\n<span class=\"p\">}</span>\n<span class=\"nx\">$</span><span class=\"p\">.</span><span class=\"nx\">ajaxSetup</span><span class=\"p\">({</span>\n<span class=\"w\">    </span><span class=\"nx\">beforeSend</span><span class=\"o\">:</span><span class=\"w\"> </span><span class=\"kd\">function</span><span class=\"p\">(</span><span class=\"nx\">xhr</span><span class=\"p\">,</span><span class=\"w\"> </span><span class=\"nx\">settings</span><span class=\"p\">)</span><span class=\"w\"> </span><span class=\"p\">{</span>\n<span class=\"w\">        </span><span class=\"k\">if</span><span class=\"w\"> </span><span class=\"p\">(</span><span class=\"o\">!</span><span class=\"nx\">csrfSafeMethod</span><span class=\"p\">(</span><span class=\"nx\">settings</span><span class=\"p\">.</span><span class=\"nx\">type</span><span class=\"p\">)</span><span class=\"w\"> </span><span class=\"o\">&amp;&amp;</span><span class=\"w\"> </span><span class=\"o\">!</span><span class=\"k\">this</span><span class=\"p\">.</span><span class=\"nx\">crossDomain</span><span class=\"p\">)</span><span class=\"w\"> </span><span class=\"p\">{</span>\n<span class=\"w\">            </span><span class=\"nx\">xhr</span><span class=\"p\">.</span><span class=\"nx\">setRequestHeader</span><span class=\"p\">(</span><span class=\"s2\">&quot;X-CSRFToken&quot;</span><span class=\"p\">,</span><span class=\"w\"> </span><span class=\"nx\">csrftoken</span><span class=\"p\">);</span>\n<span class=\"w\">        </span><span class=\"p\">}</span>\n<span class=\"w\">    </span><span class=\"p\">}</span>\n<span class=\"p\">});</span>\n</code></pre></div>\n<p>AngularJS 1.1.3 以降を使っている場合は、以下のクッキーとヘッダ名で <code class=\"docutils literal notranslate\"><span class=\"pre\">$http</span></code> プロバイダを設定すれば十分です。</p>\n<div class=\"code-block\" data-language=\"javascript\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">JavaScript</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"JavaScript code\"><code><span class=\"nx\">$httpProvider</span><span class=\"p\">.</span><span class=\"nx\">defaults</span><span class=\"p\">.</span><span class=\"nx\">xsrfCookieName</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"s1\">&#39;csrftoken&#39;</span><span class=\"p\">;</span>\n<span class=\"nx\">$httpProvider</span><span class=\"p\">.</span><span class=\"nx\">defaults</span><span class=\"p\">.</span><span class=\"nx\">xsrfHeaderName</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"s1\">&#39;X-CSRFToken&#39;</span><span class=\"p\">;</span>\n</code></pre></div>\n</section>\n</section>\n<section id=\"using-csrf-in-jinja2-templates\">\n<h3>Jinja2 テンプレートで CSRF を使用する<a class=\"heading-anchor\" href=\"#using-csrf-in-jinja2-templates\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Django の <a class=\"reference internal\" href=\"/ja/2.1/topics/templates/#django.template.backends.jinja2.Jinja2\" title=\"django.template.backends.jinja2.Jinja2\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">Jinja2</span></code></a> テンプレートバックエンドは、すべてのテンプレートのコンテキストに <code class=\"docutils literal notranslate\"><span class=\"pre\">{{</span> <span class=\"pre\">csrf_input</span> <span class=\"pre\">}}</span></code> を追加します。これは、Django テンプレート言語内の <code class=\"docutils literal notranslate\"><span class=\"pre\">{%</span> <span class=\"pre\">csrf_token</span> <span class=\"pre\">%}</span></code> と同じ意味です。例えば:</p>\n<div class=\"code-block\" data-language=\"html+jinja\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Html Jinja</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Html Jinja code\"><code><span class=\"p\">&lt;</span><span class=\"nt\">form</span> <span class=\"na\">method</span><span class=\"o\">=</span><span class=\"s\">&quot;post&quot;</span><span class=\"p\">&gt;</span><span class=\"cp\">{{</span> <span class=\"nv\">csrf_input</span> <span class=\"cp\">}}</span>\n</code></pre></div>\n</section>\n<section id=\"module-django.views.decorators.csrf\">\n<span id=\"the-decorator-method\"></span><h3>デコレータメソッド<a class=\"heading-anchor\" href=\"#module-django.views.decorators.csrf\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>全体を保護するために <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code> を追加する代わりに、保護を必要とする特定のビューにおいて、(まったく同じ機能を持つ) <code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_protect</span></code> デコレータを使えます。アウトプット内に CSRF トークンを挿入するビューと、POST フォームデータを受け入れるビューの両方で使用する必要があります (多くの場合同じビュー関数ですが、そうでない場合もあります)。</p>\n<p>デコレータ自体で使うことは <strong>非推奨</strong> です。もし使い忘れた場合、セキュリティホールを抱えることになるからです。二重対策として両方を使うのは構いませんが、わずかにオーバーヘッドが増加します。</p>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.views.decorators.csrf.csrf_protect\">\n<span class=\"sig-name descname\"><span class=\"pre\">csrf_protect</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">view</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.views.decorators.csrf.csrf_protect\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>ビューに対する <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code> の保護を提供するデコレータです。</p>\n<p>使い方は以下の通りです:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.shortcuts</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">render</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.views.decorators.csrf</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">csrf_protect</span>\n\n<span class=\"nd\">@csrf_protect</span>\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">my_view</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n    <span class=\"n\">c</span> <span class=\"o\">=</span> <span class=\"p\">{}</span>\n    <span class=\"c1\"># ...</span>\n    <span class=\"k\">return</span> <span class=\"n\">render</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">,</span> <span class=\"s2\">&quot;a_template.html&quot;</span><span class=\"p\">,</span> <span class=\"n\">c</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>クラスベースのビューを使っている場合は、 <a class=\"reference internal\" href=\"/ja/2.1/topics/class-based-views/intro/#id1\"><span class=\"std std-ref\">Decorating class-based views</span></a> を参照してください。</p>\n</dd></dl>\n\n</section>\n</section>\n<section id=\"rejected-requests\">\n<span id=\"csrf-rejected-requests\"></span><h2>拒否されたリクエスト<a class=\"heading-anchor\" href=\"#rejected-requests\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>受け取ったリクエストが <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code> による認証に失敗した場合、デフォルトでは、ユーザーには '403 Forbidden' レスポンスが送信されます。これは通常、本当にクロスサイトリクエストフォージェリが行われたか、プログラミングのミスによって POST フォームに CSRF トークンが含まれていない場合に発生します。</p>\n<p>けれども、エラーページがあまり親切ではないので、このような場面を処理 するために、自作のビューを設定することができます。 そうするには、単に settings の <a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_FAILURE_VIEW\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_FAILURE_VIEW</span></code></a> を設定してください。</p>\n<p>CSRF failures are logged as warnings to the <a class=\"reference internal\" href=\"/ja/2.1/topics/logging/#django-security-logger\"><span class=\"std std-ref\">django.security.csrf</span></a> logger.</p>\n</section>\n<section id=\"how-it-works\">\n<span id=\"how-csrf-works\"></span><h2>How it works<a class=\"heading-anchor\" href=\"#how-it-works\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>The CSRF protection is based on the following things:</p>\n<ol class=\"arabic\">\n<li><p>A CSRF cookie that is based on a random secret value, which other sites\nwill not have access to.</p>\n<p>This cookie is set by <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code>. It is sent with every\nresponse that has called <code class=\"docutils literal notranslate\"><span class=\"pre\">django.middleware.csrf.get_token()</span></code> (the\nfunction used internally to retrieve the CSRF token), if it wasn't already\nset on the request.</p>\n<p>In order to protect against <a class=\"reference external\" href=\"http://breachattack.com/\">BREACH</a> attacks, the token is not simply the\nsecret; a random salt is prepended to the secret and used to scramble it.</p>\n<p>For security reasons, the value of the secret is changed each time a\nuser logs in.</p>\n</li>\n<li><p>A hidden form field with the name 'csrfmiddlewaretoken' present in all\noutgoing POST forms. The value of this field is, again, the value of the\nsecret, with a salt which is both added to it and used to scramble it. The\nsalt is regenerated on every call to <code class=\"docutils literal notranslate\"><span class=\"pre\">get_token()</span></code> so that the form field\nvalue is changed in every such response.</p>\n<p>This part is done by the template tag.</p>\n</li>\n<li><p>For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or\nTRACE, a CSRF cookie must be present, and the 'csrfmiddlewaretoken' field\nmust be present and correct. If it isn't, the user will get a 403 error.</p>\n<p>When validating the 'csrfmiddlewaretoken' field value, only the secret,\nnot the full token, is compared with the secret in the cookie value.\nThis allows the use of ever-changing tokens. While each request may use its\nown token, the secret remains common to all.</p>\n<p>This check is done by <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code>.</p>\n</li>\n<li><p>In addition, for HTTPS requests, strict referer checking is done by\n<code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code>. This means that even if a subdomain can set or\nmodify cookies on your domain, it can't force a user to post to your\napplication since that request won't come from your own exact domain.</p>\n<p>This also addresses a man-in-the-middle attack that's possible under HTTPS\nwhen using a session independent secret, due to the fact that HTTP\n<code class=\"docutils literal notranslate\"><span class=\"pre\">Set-Cookie</span></code> headers are (unfortunately) accepted by clients even when\nthey are talking to a site under HTTPS. (Referer checking is not done for\nHTTP requests because the presence of the <code class=\"docutils literal notranslate\"><span class=\"pre\">Referer</span></code> header isn't reliable\nenough under HTTP.)</p>\n<p>If the <a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_COOKIE_DOMAIN\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_DOMAIN</span></code></a> setting is set, the referer is compared\nagainst it. This setting supports subdomains. For example,\n<code class=\"docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_DOMAIN</span> <span class=\"pre\">=</span> <span class=\"pre\">'.example.com'</span></code> will allow POST requests from\n<code class=\"docutils literal notranslate\"><span class=\"pre\">www.example.com</span></code> and <code class=\"docutils literal notranslate\"><span class=\"pre\">api.example.com</span></code>. If the setting is not set, then\nthe referer must match the HTTP <code class=\"docutils literal notranslate\"><span class=\"pre\">Host</span></code> header.</p>\n<p>Expanding the accepted referers beyond the current host or cookie domain can\nbe done with the <a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_TRUSTED_ORIGINS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_TRUSTED_ORIGINS</span></code></a> setting.</p>\n</li>\n</ol>\n<p>This ensures that only forms that have originated from trusted domains can be\nused to POST data back.</p>\n<p>It deliberately ignores GET requests (and other requests that are defined as\n'safe' by <span class=\"target\" id=\"index-1\"></span><a class=\"rfc reference external\" href=\"https://datatracker.ietf.org/doc/html/rfc7231.html\"><strong>RFC 7231</strong></a>). These requests ought never to have any potentially\ndangerous side effects , and so a CSRF attack with a GET request ought to be\nharmless. <span class=\"target\" id=\"index-2\"></span><a class=\"rfc reference external\" href=\"https://datatracker.ietf.org/doc/html/rfc7231.html\"><strong>RFC 7231</strong></a> defines POST, PUT, and DELETE as 'unsafe', and all other\nmethods are also assumed to be unsafe, for maximum protection.</p>\n<p>The CSRF protection cannot protect against man-in-the-middle attacks, so use\n<a class=\"reference internal\" href=\"/ja/2.1/topics/security/#security-recommendation-ssl\"><span class=\"std std-ref\">HTTPS</span></a> with\n<a class=\"reference internal\" href=\"/ja/2.1/ref/middleware/#http-strict-transport-security\"><span class=\"std std-ref\">HTTP Strict Transport Security</span></a>. It also assumes <a class=\"reference internal\" href=\"/ja/2.1/topics/security/#host-headers-virtual-hosting\"><span class=\"std std-ref\">validation of\nthe HOST header</span></a> and that there aren't any\n<a class=\"reference internal\" href=\"/ja/2.1/topics/security/#cross-site-scripting\"><span class=\"std std-ref\">cross-site scripting vulnerabilities</span></a> on your site\n(because XSS vulnerabilities already let an attacker do anything a CSRF\nvulnerability allows and much worse).</p>\n<aside class=\"admonition-removing-the-referer-header admonition\">\n<p class=\"admonition-title\">Removing the <code class=\"docutils literal notranslate\"><span class=\"pre\">Referer</span></code> header</p>\n<p>To avoid disclosing the referrer URL to third-party sites, you might want\nto <a class=\"reference external\" href=\"https://www.w3.org/TR/referrer-policy/#referrer-policy-delivery\">disable the referer</a> on your site's <code class=\"docutils literal notranslate\"><span class=\"pre\">&lt;a&gt;</span></code> tags. For example, you\nmight use the <code class=\"docutils literal notranslate\"><span class=\"pre\">&lt;meta</span> <span class=\"pre\">name=&quot;referrer&quot;</span> <span class=\"pre\">content=&quot;no-referrer&quot;&gt;</span></code> tag or\ninclude the <code class=\"docutils literal notranslate\"><span class=\"pre\">Referrer-Policy:</span> <span class=\"pre\">no-referrer</span></code> header. Due to the CSRF\nprotection's strict referer checking on HTTPS requests, those techniques\ncause a CSRF failure on requests with 'unsafe' methods. Instead, use\nalternatives like <code class=\"docutils literal notranslate\"><span class=\"pre\">&lt;a</span> <span class=\"pre\">rel=&quot;noreferrer&quot;</span> <span class=\"pre\">...&gt;&quot;</span></code> for links to third-party\nsites.</p>\n</aside>\n</section>\n<section id=\"caching\">\n<h2>Caching<a class=\"heading-anchor\" href=\"#caching\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>If the <a class=\"reference internal\" href=\"/ja/2.1/ref/templates/builtins/#std-templatetag-csrf_token\"><code class=\"xref std std-ttag docutils literal notranslate\"><span class=\"pre\">csrf_token</span></code></a> template tag is used by a template (or the\n<code class=\"docutils literal notranslate\"><span class=\"pre\">get_token</span></code> function is called some other way), <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code> will\nadd a cookie and a <code class=\"docutils literal notranslate\"><span class=\"pre\">Vary:</span> <span class=\"pre\">Cookie</span></code> header to the response. This means that the\nmiddleware will play well with the cache middleware if it is used as instructed\n(<code class=\"docutils literal notranslate\"><span class=\"pre\">UpdateCacheMiddleware</span></code> goes before all other middleware).</p>\n<p>However, if you use cache decorators on individual views, the CSRF middleware\nwill not yet have been able to set the Vary header or the CSRF cookie, and the\nresponse will be cached without either one. In this case, on any views that\nwill require a CSRF token to be inserted you should use the\n<a class=\"reference internal\" href=\"#django.views.decorators.csrf.csrf_protect\" title=\"django.views.decorators.csrf.csrf_protect\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">django.views.decorators.csrf.csrf_protect()</span></code></a> decorator first:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.views.decorators.cache</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">cache_page</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.views.decorators.csrf</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">csrf_protect</span>\n\n<span class=\"nd\">@cache_page</span><span class=\"p\">(</span><span class=\"mi\">60</span> <span class=\"o\">*</span> <span class=\"mi\">15</span><span class=\"p\">)</span>\n<span class=\"nd\">@csrf_protect</span>\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">my_view</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n    <span class=\"o\">...</span>\n</code></pre></div>\n<p>クラスベースのビューを使っている場合は、 <a class=\"reference internal\" href=\"/ja/2.1/topics/class-based-views/intro/#id1\"><span class=\"std std-ref\">Decorating class-based views</span></a> を参照してください。</p>\n</section>\n<section id=\"testing\">\n<h2>テスト<a class=\"heading-anchor\" href=\"#testing\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>The <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code> will usually be a big hindrance to testing view\nfunctions, due to the need for the CSRF token which must be sent with every POST\nrequest.  For this reason, Django's HTTP client for tests has been modified to\nset a flag on requests which relaxes the middleware and the <code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_protect</span></code>\ndecorator so that they no longer rejects requests.  In every other respect\n(e.g. sending cookies etc.), they behave the same.</p>\n<p>If, for some reason, you <em>want</em> the test client to perform CSRF\nchecks, you can create an instance of the test client that enforces\nCSRF checks:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.test</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">Client</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"n\">csrf_client</span> <span class=\"o\">=</span> <span class=\"n\">Client</span><span class=\"p\">(</span><span class=\"n\">enforce_csrf_checks</span><span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">)</span>\n</code></pre></div>\n</section>\n<section id=\"limitations\">\n<span id=\"csrf-limitations\"></span><h2>制限事項<a class=\"heading-anchor\" href=\"#limitations\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Subdomains within a site will be able to set cookies on the client for the whole\ndomain.  By setting the cookie and using a corresponding token, subdomains will\nbe able to circumvent the CSRF protection.  The only way to avoid this is to\nensure that subdomains are controlled by trusted users (or, are at least unable\nto set cookies).  Note that even without CSRF, there are other vulnerabilities,\nsuch as session fixation, that make giving subdomains to untrusted parties a bad\nidea, and these vulnerabilities cannot easily be fixed with current browsers.</p>\n</section>\n<section id=\"edge-cases\">\n<h2>Edge cases<a class=\"heading-anchor\" href=\"#edge-cases\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Certain views can have unusual requirements that mean they don't fit the normal\npattern envisaged here. A number of utilities can be useful in these\nsituations. The scenarios they might be needed in are described in the following\nsection.</p>\n<section id=\"utilities\">\n<h3>Utilities<a class=\"heading-anchor\" href=\"#utilities\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>The examples below assume you are using function-based views. If you\nare working with class-based views, you can refer to <a class=\"reference internal\" href=\"/ja/2.1/topics/class-based-views/intro/#id1\"><span class=\"std std-ref\">Decorating\nclass-based views</span></a>.</p>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.views.decorators.csrf.csrf_exempt\">\n<span class=\"sig-name descname\"><span class=\"pre\">csrf_exempt</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">view</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.views.decorators.csrf.csrf_exempt\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>This decorator marks a view as being exempt from the protection ensured by\nthe middleware. Example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.http</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">HttpResponse</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.views.decorators.csrf</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">csrf_exempt</span>\n\n<span class=\"nd\">@csrf_exempt</span>\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">my_view</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n    <span class=\"k\">return</span> <span class=\"n\">HttpResponse</span><span class=\"p\">(</span><span class=\"s1\">&#39;Hello world&#39;</span><span class=\"p\">)</span>\n</code></pre></div>\n</dd></dl>\n\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.views.decorators.csrf.requires_csrf_token\">\n<span class=\"sig-name descname\"><span class=\"pre\">requires_csrf_token</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">view</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.views.decorators.csrf.requires_csrf_token\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Normally the <a class=\"reference internal\" href=\"/ja/2.1/ref/templates/builtins/#std-templatetag-csrf_token\"><code class=\"xref std std-ttag docutils literal notranslate\"><span class=\"pre\">csrf_token</span></code></a> template tag will not work if\n<code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware.process_view</span></code> or an equivalent like <code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_protect</span></code>\nhas not run. The view decorator <code class=\"docutils literal notranslate\"><span class=\"pre\">requires_csrf_token</span></code> can be used to\nensure the template tag does work. This decorator works similarly to\n<code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_protect</span></code>, but never rejects an incoming request.</p>\n<p>実装例:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.shortcuts</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">render</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.views.decorators.csrf</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">requires_csrf_token</span>\n\n<span class=\"nd\">@requires_csrf_token</span>\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">my_view</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n    <span class=\"n\">c</span> <span class=\"o\">=</span> <span class=\"p\">{}</span>\n    <span class=\"c1\"># ...</span>\n    <span class=\"k\">return</span> <span class=\"n\">render</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">,</span> <span class=\"s2\">&quot;a_template.html&quot;</span><span class=\"p\">,</span> <span class=\"n\">c</span><span class=\"p\">)</span>\n</code></pre></div>\n</dd></dl>\n\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.views.decorators.csrf.ensure_csrf_cookie\">\n<span class=\"sig-name descname\"><span class=\"pre\">ensure_csrf_cookie</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">view</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.views.decorators.csrf.ensure_csrf_cookie\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>This decorator forces a view to send the CSRF cookie.</p>\n</dd></dl>\n\n</section>\n<section id=\"scenarios\">\n<h3>Scenarios<a class=\"heading-anchor\" href=\"#scenarios\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<section id=\"csrf-protection-should-be-disabled-for-just-a-few-views\">\n<h4>CSRF protection should be disabled for just a few views<a class=\"heading-anchor\" href=\"#csrf-protection-should-be-disabled-for-just-a-few-views\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>Most views requires CSRF protection, but a few do not.</p>\n<p>Solution: rather than disabling the middleware and applying <code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_protect</span></code> to\nall the views that need it, enable the middleware and use\n<a class=\"reference internal\" href=\"#django.views.decorators.csrf.csrf_exempt\" title=\"django.views.decorators.csrf.csrf_exempt\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">csrf_exempt()</span></code></a>.</p>\n</section>\n<section id=\"csrfviewmiddleware-process-view-not-used\">\n<h4>CsrfViewMiddleware.process_view not used<a class=\"heading-anchor\" href=\"#csrfviewmiddleware-process-view-not-used\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>There are cases when <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware.process_view</span></code> may not have run\nbefore your view is run - 404 and 500 handlers, for example - but you still\nneed the CSRF token in a form.</p>\n<p>Solution: use <a class=\"reference internal\" href=\"#django.views.decorators.csrf.requires_csrf_token\" title=\"django.views.decorators.csrf.requires_csrf_token\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">requires_csrf_token()</span></code></a></p>\n</section>\n<section id=\"unprotected-view-needs-the-csrf-token\">\n<h4>Unprotected view needs the CSRF token<a class=\"heading-anchor\" href=\"#unprotected-view-needs-the-csrf-token\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>There may be some views that are unprotected and have been exempted by\n<code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_exempt</span></code>, but still need to include the CSRF token.</p>\n<p>Solution: use <a class=\"reference internal\" href=\"#django.views.decorators.csrf.csrf_exempt\" title=\"django.views.decorators.csrf.csrf_exempt\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">csrf_exempt()</span></code></a> followed by\n<a class=\"reference internal\" href=\"#django.views.decorators.csrf.requires_csrf_token\" title=\"django.views.decorators.csrf.requires_csrf_token\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">requires_csrf_token()</span></code></a>. (i.e. <code class=\"docutils literal notranslate\"><span class=\"pre\">requires_csrf_token</span></code>\nshould be the innermost decorator).</p>\n</section>\n<section id=\"view-needs-protection-for-one-path\">\n<h4>View needs protection for one path<a class=\"heading-anchor\" href=\"#view-needs-protection-for-one-path\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>A view needs CSRF protection under one set of conditions only, and mustn't have\nit for the rest of the time.</p>\n<p>Solution: use <a class=\"reference internal\" href=\"#django.views.decorators.csrf.csrf_exempt\" title=\"django.views.decorators.csrf.csrf_exempt\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">csrf_exempt()</span></code></a> for the whole\nview function, and <a class=\"reference internal\" href=\"#django.views.decorators.csrf.csrf_protect\" title=\"django.views.decorators.csrf.csrf_protect\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">csrf_protect()</span></code></a> for the\npath within it that needs protection. Example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.views.decorators.csrf</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">csrf_exempt</span><span class=\"p\">,</span> <span class=\"n\">csrf_protect</span>\n\n<span class=\"nd\">@csrf_exempt</span>\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">my_view</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n\n    <span class=\"nd\">@csrf_protect</span>\n    <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">protected_path</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n        <span class=\"n\">do_something</span><span class=\"p\">()</span>\n\n    <span class=\"k\">if</span> <span class=\"n\">some_condition</span><span class=\"p\">():</span>\n       <span class=\"k\">return</span> <span class=\"n\">protected_path</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">)</span>\n    <span class=\"k\">else</span><span class=\"p\">:</span>\n       <span class=\"n\">do_something_else</span><span class=\"p\">()</span>\n</code></pre></div>\n</section>\n<section id=\"page-uses-ajax-without-any-html-form\">\n<h4>Page uses AJAX without any HTML form<a class=\"heading-anchor\" href=\"#page-uses-ajax-without-any-html-form\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>A page makes a POST request via AJAX, and the page does not have an HTML form\nwith a <a class=\"reference internal\" href=\"/ja/2.1/ref/templates/builtins/#std-templatetag-csrf_token\"><code class=\"xref std std-ttag docutils literal notranslate\"><span class=\"pre\">csrf_token</span></code></a> that would cause the required CSRF cookie to be sent.</p>\n<p>Solution: use <a class=\"reference internal\" href=\"#django.views.decorators.csrf.ensure_csrf_cookie\" title=\"django.views.decorators.csrf.ensure_csrf_cookie\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">ensure_csrf_cookie()</span></code></a> on the\nview that sends the page.</p>\n</section>\n</section>\n</section>\n<section id=\"contrib-and-reusable-apps\">\n<h2>Contrib and reusable apps<a class=\"heading-anchor\" href=\"#contrib-and-reusable-apps\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Because it is possible for the developer to turn off the <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code>,\nall relevant views in contrib apps use the <code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_protect</span></code> decorator to ensure\nthe security of these applications against CSRF.  It is recommended that the\ndevelopers of other reusable apps that want the same guarantees also use the\n<code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_protect</span></code> decorator on their views.</p>\n</section>\n<section id=\"settings\">\n<h2>設定<a class=\"heading-anchor\" href=\"#settings\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>A number of settings can be used to control Django's CSRF behavior:</p>\n<ul class=\"simple\">\n<li><p><a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_COOKIE_AGE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_AGE</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_COOKIE_DOMAIN\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_DOMAIN</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_COOKIE_HTTPONLY\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_HTTPONLY</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_COOKIE_NAME\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_NAME</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_COOKIE_PATH\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_PATH</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_COOKIE_SAMESITE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_SAMESITE</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_COOKIE_SECURE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_SECURE</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_FAILURE_VIEW\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_FAILURE_VIEW</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_HEADER_NAME\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_HEADER_NAME</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_TRUSTED_ORIGINS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_TRUSTED_ORIGINS</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_USE_SESSIONS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_USE_SESSIONS</span></code></a></p></li>\n</ul>\n</section>\n<section id=\"frequently-asked-questions\">\n<h2>Frequently Asked Questions<a class=\"heading-anchor\" href=\"#frequently-asked-questions\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<section id=\"is-posting-an-arbitrary-csrf-token-pair-cookie-and-post-data-a-vulnerability\">\n<h3>Is posting an arbitrary CSRF token pair (cookie and POST data) a vulnerability?<a class=\"heading-anchor\" href=\"#is-posting-an-arbitrary-csrf-token-pair-cookie-and-post-data-a-vulnerability\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>No, this is by design. Without a man-in-the-middle attack, there is no way for\nan attacker to send a CSRF token cookie to a victim's browser, so a successful\nattack would need to obtain the victim's browser's cookie via XSS or similar,\nin which case an attacker usually doesn't need CSRF attacks.</p>\n<p>Some security audit tools flag this as a problem but as mentioned before, an\nattacker cannot steal a user's browser's CSRF cookie. &quot;Stealing&quot; or modifying\n<em>your own</em> token using Firebug, Chrome dev tools, etc. isn't a vulnerability.</p>\n</section>\n<section id=\"is-it-a-problem-that-django-s-csrf-protection-isn-t-linked-to-a-session-by-default\">\n<h3>Is it a problem that Django's CSRF protection isn't linked to a session by default?<a class=\"heading-anchor\" href=\"#is-it-a-problem-that-django-s-csrf-protection-isn-t-linked-to-a-session-by-default\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>No, this is by design. Not linking CSRF protection to a session allows using\nthe protection on sites such as a pastebin that allow submissions from\nanonymous users which don't have a session.</p>\n<p>If you wish to store the CSRF token in the user's session, use the\n<a class=\"reference internal\" href=\"/ja/2.1/ref/settings/#std-setting-CSRF_USE_SESSIONS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_USE_SESSIONS</span></code></a> setting.</p>\n</section>\n<section id=\"why-might-a-user-encounter-a-csrf-validation-failure-after-logging-in\">\n<h3>Why might a user encounter a CSRF validation failure after logging in?<a class=\"heading-anchor\" href=\"#why-might-a-user-encounter-a-csrf-validation-failure-after-logging-in\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>For security reasons, CSRF tokens are rotated each time a user logs in. Any\npage with a form generated before a login will have an old, invalid CSRF token\nand need to be reloaded. This might happen if a user uses the back button after\na login or if they log in a different browser tab.</p>\n</section>\n</section>","rootId":"module-django.middleware.csrf","toc":[{"title":"使用方法","anchor":"how-to-use-it","children":[{"title":"AJAX","anchor":"ajax","children":[{"title":"Acquiring the token if CSRF_USE_SESSIONS and CSRF_COOKIE_HTTPONLY are False","anchor":"acquiring-the-token-if-csrf-use-sessions-and-csrf-cookie-httponly-are-false","children":[]},{"title":"Acquiring the token if CSRF_USE_SESSIONS or CSRF_COOKIE_HTTPONLY is True","anchor":"acquiring-the-token-if-csrf-use-sessions-or-csrf-cookie-httponly-is-true","children":[]},{"title":"Setting the token on the AJAX request","anchor":"setting-the-token-on-the-ajax-request","children":[]}]},{"title":"Jinja2 テンプレートで CSRF を使用する","anchor":"using-csrf-in-jinja2-templates","children":[]},{"title":"デコレータメソッド","anchor":"module-django.views.decorators.csrf","children":[]}]},{"title":"拒否されたリクエスト","anchor":"rejected-requests","children":[]},{"title":"How it works","anchor":"how-it-works","children":[]},{"title":"Caching","anchor":"caching","children":[]},{"title":"テスト","anchor":"testing","children":[]},{"title":"制限事項","anchor":"limitations","children":[]},{"title":"Edge cases","anchor":"edge-cases","children":[{"title":"Utilities","anchor":"utilities","children":[]},{"title":"Scenarios","anchor":"scenarios","children":[{"title":"CSRF protection should be disabled for just a few views","anchor":"csrf-protection-should-be-disabled-for-just-a-few-views","children":[]},{"title":"CsrfViewMiddleware.process_view not used","anchor":"csrfviewmiddleware-process-view-not-used","children":[]},{"title":"Unprotected view needs the CSRF token","anchor":"unprotected-view-needs-the-csrf-token","children":[]},{"title":"View needs protection for one path","anchor":"view-needs-protection-for-one-path","children":[]},{"title":"Page uses AJAX without any HTML form","anchor":"page-uses-ajax-without-any-html-form","children":[]}]}]},{"title":"Contrib and reusable apps","anchor":"contrib-and-reusable-apps","children":[]},{"title":"設定","anchor":"settings","children":[]},{"title":"Frequently Asked Questions","anchor":"frequently-asked-questions","children":[{"title":"Is posting an arbitrary CSRF token pair (cookie and POST data) a vulnerability?","anchor":"is-posting-an-arbitrary-csrf-token-pair-cookie-and-post-data-a-vulnerability","children":[]},{"title":"Is it a problem that Django's CSRF protection isn't linked to a session by default?","anchor":"is-it-a-problem-that-django-s-csrf-protection-isn-t-linked-to-a-session-by-default","children":[]},{"title":"Why might a user encounter a CSRF validation failure after logging in?","anchor":"why-might-a-user-encounter-a-csrf-validation-failure-after-logging-in","children":[]}]}],"breadcrumbs":[{"docname":"ref/index","title":"API Reference","url":"/ja/2.1/ref/"}],"prev":{"docname":"ref/contrib/syndication","title":"The syndication feed framework","url":"/ja/2.1/ref/contrib/syndication/"},"next":{"docname":"ref/databases","title":"データベース","url":"/ja/2.1/ref/databases/"},"formats":{"html":"/ja/2.1/ref/csrf/","markdown":"/ja/2.1/ref/csrf.md","json":"/ja/2.1/ref/csrf.json"},"source":"https://github.com/django/django/blob/stable/2.1.x/docs/ref/csrf.txt","official":"https://docs.djangoproject.com/ja/2.1/ref/csrf/","inVersions":["6.1","6.0","5.2","5.1","5.0","4.2","4.1","4.0","3.2","3.1","3.0","2.2","2.1","2.0","1.11","1.10","1.9"],"inLocales":["en","zh-hans","fr","ja","id","pt-br","ko","es","el","pl"]}