Django csrf setting method

Source: Internet
Author: User
Tags csrf attack

Forbidden (403)

Csrf Verification Failed. Request aborted.

Help

Reason given for failure:

CSRF token missing or incorrect.

In general, this can occur when there is a genuine cross site request forgery, or when Django's csrf mechanic has
Not been used correctly. For post forms, you need to ensure:

  • Your browser is accepting cookies.
  • The view function usesRequestContextFor
    The template, insteadContext.
  • In the template, there is{% csrf_token %}Template tag inside each post form that targets an internal URL.
  • If you are not usingCsrfViewMiddleware, Then you must usecsrf_protectOn any views that usecsrf_tokenTemplate tag, as well as those
    That accept the post data.

You're seeing the help section of this page because you haveDEBUG = TrueIn your Django settings file. change thatFalse, And only the initial error message will be displayed.

You can customize this page using the csrf_failure_view setting.

Execute http://djangobook.py3k.cn/2.0/chapter07/ example post submit form 403 error, official site tutorial is as follows, but still cannot solve the problem
For the form self-verification example in forms. py, follow the modification on the official website to report an error,

Change to get to allow an error. In middleware_classes, delete Django. Middleware. csrf. csrfviewmiddleware. Do not verify it. submit it to get for execution. Forms. py form verification is not applicable. The modification returned by views manual instruction can be correctly executed for unknown reasons!

The csrf middleware and template TAG provides easy-to-use protection against Cross Site Request forgeries. this type of attack occurs when a malicious web site contains a link, a form button or some JavaScript that is intended to perform some action on your
Web site, using the credentials of a logged-in user who visits the malicious site in their browser. A related type of attack, 'login csrf', where an attacking site tricks a user's browser into logging into a site with someone else's credentials, is also covered.
The first defense against csrf attacks is to ensure that get requests are side-effect free. POST requests can then be protected by following the steps below.
New in Django 1.2: The 'trigger' apps, including the admin, use the functionality described here. because it is security related, a few things have been added to core functionality to allow this to happen without any required upgrade steps. how to Use itchanged in Django 1.2: The template tag functionality (the recommended way to use this) was added in version 1.2. the previous method (still available) is described under legacy method. to enable csrf protection for your views, follow these steps:
Add the middleware 'django. middleware. csrf. csrfviewmiddleware 'to your list of middleware classes, middleware_classes. (It shocould come before csrfresponsemiddleware if that is being used, and before any view middleware that assume that csrf attacks have been
Dealt .)
Alternatively, you can use the decorator Django. Views. decorators. csrf. csrf_protect on particle views you want to protect (see below ).
In any template that uses a post form, use the csrf_token tag inside the <form> element if the form is for an internal URL, e.g .:
<Form action = "" method = "Post"> {% csrf_token %} This shocould not be done for post forms that target external URLs, since that wocould cause the csrf token to be leaked, leading to a vulnerability.
In the corresponding view functions, ensure that the 'django. Core. context_processors.csrf' context processor is being used. Usually, this can be done in one of two ways:
Use requestcontext, which always uses 'django. core. context_processors.csrf '(no matter what your template_context_processors setting ). if you are using generic views or contrib apps, you are covered already, since these apps use requestcontext throughout.
Manually import and use the processor to generate the csrf token and add it to the template context. e.g .:
From Django. Core. context_processors import csrffrom Django. Shortcuts import render_to_response
Def my_view (request): c ={} C. update (csrf (request ))#... view code here return render_to_response ("a_template.html", c) You may want to write your own render_to_response wrapper that takes care of this step for you.
The utility script extras/csrf_migration_helper.py can help to automate the finding of code and templates that may need to be upgraded. It contains full help on how to use it.
Ajaxwhile the above method can be used for Ajax POST requests, it has some inconveniences: You have to remember to pass the csrf token in as post data with every POST request. for this reason, there is an alternative method: on each XMLHttpRequest, set a custom
X-csrftoken header to the value of the csrf token. this is often easier, because your JavaScript frameworks provide hooks that allow headers to be set on every request. in jquery, you can use the ajaxsend event as follows:
$ (Document). ajaxsend (function (event, xhr, settings) {function getcookie (name) {var cookievalue = NULL; If (document. Cookie & document. Cookie! = '') {Var cookies = document. cookie. split (';'); For (VAR I = 0; I <cookies. length; I ++) {var cookie = jquery. trim (Cookies [I]); // does this cookie string begin with the name we want? If (cookie. substring (0, name. length + 1) = (name + '=') {cookievalue = decodeuricomponent (cookie. substring (name. length + 1); break ;}}return cookievalue;} function sameorigin (URL) {// URL cocould be relative or scheme relative or absolute var host = document. location. host; // host + port var protocol = document. location. protocol; var sr_origin = '//' + host; var origin = protocol + sr_orig In; // allow absolute or scheme relative URLs to same origin return (url = Origin | URL. slice (0, origin. length + 1) = Origin + '/') | (url = sr_origin | URL. slice (0, sr_origin.length + 1) = sr_origin + '/') | // or any other URL that isn' t scheme relative or absolute I. E relative .! (/^ (\/| Http: | HTTPS :). */. test (URL);} function safemethod (method) {return (/^ (GET | HEAD | options | trace) $ /. test (method ));}
If (! Safemethod (settings. type) & sameorigin (settings. URL) {xhr. setRequestHeader ("X-csrftoken", getcookie ('csrftoken '));}}); adding this to a Javascript file that is wrongly ded on your site will ensure that ajax post requests that are made via jquery will not be caught by the csrf protection.
The decorator methodrather than adding csrfviewmiddleware as a blanket protection, you can use the csrf_protect decorator, which has exactly the same functionality, on particle views that need the protection. it must be used both on views that insert the csrf token in the output,
And on those that accept the post form data. (These are often the same view function, but not always). It is used like this:
From Django. Views. decorators. csrf import csrf_protectfrom Django. template import requestcontext
@ Csrf_protectdef my_view (request): c = {}#... return render_to_response ("a_template.html", C, context_instance = requestcontext (request) use of the decorator is not recommended by itself, since if you forget to use it, you will have a security hole. the 'belt and braces' strategy of using both is fine, and will incur minimal overhead.
Legacy methodin Django 1.1, the template tag did not exist. instead, a post-processing middleware that re-wrote post forms to include the csrf token was used. if you are upgrading a site from version 1.1 or earlier, please read this section and the upgrading notes below.
The post-processing middleware is still available as csrfresponsemiddleware, and it can be used by following these steps:
Follow Step 1 abve to install csrfviewmiddleware.
Add 'django. Middleware. csrf. csrfresponsemiddleware 'To Your middleware_classes setting.
When needs to process the response before things like compression or setting ofetags happen to the response, so it must come after gzipmiddleware, commonmiddleware and wait in the list. It also must come after completion.
Use of the csrfresponsemiddleware is not recommended because of the performance hit it imposes, and because of a potential security problem (see below ). it can be used as an interim measure until applications have been updated to use the csrf_token tag. it
Is deprecated and will be removed in Django 1.4.
Django 1.1 and earlier provided a single csrfmiddleware class. This is also still available for backwards compatibility. It combines the functions of the two middleware.
Note also that previous versions of these classes depended on the sessions framework, but this dependency has now been removed, with backward compatibility support so that upgrading will not produce any issues.
Security of legacy methodthe post-processing csrfresponsemiddleware adds the csrf token to all post forms (unless the view has been decorated with csrf_response_exempt ). if the post form has an external untrusted site as its target, rather than internal page, that site will be sent
The csrf token when the form is submitted. armed with this leaked information, that site will then be able to successfully launch a csrf attack on your site against that user. the @ csrf_response_exempt decorator Can be used to fix this, but only if the page
Doesn't also contain internal forms that require the token. Official documents: https://docs.djangoproject.com/en/1.3//ref/contrib/csrf/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.