---
title: "Cómo utilizar la protección CSRF de Django"
version: 4.2
locale: es
source: https://docs.djangoproject.com/es/4.2/howto/csrf/
canonical: https://djangodocs.dev/es/4.2/howto/csrf/
---
# Cómo utilizar la protección CSRF de Django

Para aprovechar la protección CSRF en sus vistas, siga estos pasos:

1. El middleware CSRF está activado de forma predeterminada en la configuración [`MIDDLEWARE`](/es/4.2/ref/settings/#std-setting-MIDDLEWARE). Si anula esa configuración, recuerde que `'django.middleware.csrf.CsrfViewMiddleware'` debe aparecer antes de cualquier middleware de vista que asuma que se han tratado los ataques CSRF.

   Si lo desactivó, lo cual no se recomienda, puede usar [`csrf_protect()`](/es/4.2/ref/csrf/#django.views.decorators.csrf.csrf_protect) en vistas particulares que desee proteger (ver más abajo).
2. En cualquier plantilla que utilice un formulario POST, utilice la etiqueta [`csrf_token`](/es/4.2/ref/templates/builtins/#std-templatetag-csrf_token) dentro del elemento `<form>` si el formulario es para una dirección URL interna, por ejemplo:

   ```html+django
   <form method="post">{% csrf_token %}
   ```

   Esto no debe hacerse para los formularios POST que se dirigen a URL externas, ya que eso provocaría que se filtrara el token CSRF, lo que provocaría una vulnerabilidad.
3. En las funciones de vista correspondientes, asegúrese de que [`RequestContext`](/es/4.2/ref/templates/api/#django.template.RequestContext) se utiliza para representar la respuesta de modo que `{% csrf_token %}` funcione correctamente. Si está utilizando la función [`render()`](/es/4.2/topics/http/shortcuts/#django.shortcuts.render), vistas genéricas o aplicaciones contrib, ya está cubierto, ya que todas usan `RequestContext`.

## Uso de la protección CSRF con AJAX

Si bien el método anterior se puede usar para solicitudes AJAX POST, tiene algunos inconvenientes: debe recordar pasar el token CSRF como datos POST con cada solicitud POST. Por esta razón, existe un método alternativo: en cada XMLHttpRequest, establezca un encabezado personalizado `X-CSRFToken` (como se especifica en ajuste [`CSRF_HEADER_NAME`](/es/4.2/ref/settings/#std-setting-CSRF_HEADER_NAME)) el valor del valor del token CSRF. Esto suele ser más fácil porque muchos marcos de JavaScript proporcionan ganchos que permiten establecer encabezados en cada solicitud.

Primero, debe obtener el token CSRF. Cómo hacerlo depende de si la configuración [`CSRF_USE_SESSIONS`](/es/4.2/ref/settings/#std-setting-CSRF_USE_SESSIONS) y [`CSRF_COOKIE_HTTPONLY`](/es/4.2/ref/settings/#std-setting-CSRF_COOKIE_HTTPONLY) está habilitada o no.

### Obtener el token si [`CSRF_USE_SESSIONS`](/es/4.2/ref/settings/#std-setting-CSRF_USE_SESSIONS) y [`CSRF_COOKIE_HTTPONLY`](/es/4.2/ref/settings/#std-setting-CSRF_COOKIE_HTTPONLY) son `False`

La fuente recomendada para el token es la cookie `csrftoken`, que se establecerá si ha habilitado la protección CSRF para sus vistas como se describe anteriormente.

La cookie de token CSRF se denomina `csrftoken` de forma predeterminada, pero puede controlar el nombre de la cookie a través de la configuración [`CSRF_COOKIE_NAME`](/es/4.2/ref/settings/#std-setting-CSRF_COOKIE_NAME).

Puede obtener el token así:

```javascript
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // 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;
}
const csrftoken = getCookie('csrftoken');
```

El código anterior podría simplificarse utilizando la [biblioteca de cookies de JavaScript](https://github.com/js-cookie/js-cookie/) para reemplazar `getCookie`:

```javascript
const csrftoken = Cookies.get('csrftoken');
```

> **Note**
>
> El token CSRF también está presente en el DOM en forma enmascarada, pero solo si se incluye explícitamente usando [`csrf_token`](/es/4.2/ref/templates/builtins/#std-templatetag-csrf_token) en una plantilla. La cookie contiene el token canónico y desenmascarado. [`CsrfViewMiddleware`](/es/4.2/ref/middleware/#django.middleware.csrf.CsrfViewMiddleware) aceptará cualquiera de los dos. Sin embargo, para protegerse contra los ataques [BREACH](https://www.breachattack.com/), se recomienda usar un token enmascarado.

> **Warning**
>
> Si su vista no representa una plantilla que contiene la etiqueta de plantilla [`csrf_token`](/es/4.2/ref/templates/builtins/#std-templatetag-csrf_token), es posible que Django no establezca la cookie de token CSRF. Esto es común en los casos en que los formularios se agregan dinámicamente a la página. Para abordar este caso, Django proporciona un decorador de vistas que fuerza la configuración de la cookie: [`ensure_csrf_cookie()`](/es/4.2/ref/csrf/#django.views.decorators.csrf.ensure_csrf_cookie).

### Obtener el token si [`CSRF_USE_SESSIONS`](/es/4.2/ref/settings/#std-setting-CSRF_USE_SESSIONS) o [`CSRF_COOKIE_HTTPONLY`](/es/4.2/ref/settings/#std-setting-CSRF_COOKIE_HTTPONLY) es `True`

Si activa [`CSRF_USE_SESSIONS`](/es/4.2/ref/settings/#std-setting-CSRF_USE_SESSIONS) o [`CSRF_COOKIE_HTTPONLY`](/es/4.2/ref/settings/#std-setting-CSRF_COOKIE_HTTPONLY), debe incluir el token CSRF en su HTML y leer el token del DOM con JavaScript:

```html+django
{% csrf_token %}
<script>
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
</script>
```

### Configuración del token en la solicitud de AJAX

Finalmente, deberá configurar el encabezado en su solicitud AJAX. Usando la API [fetch()](https://developer.mozilla.org/en-US/docs/Web/API/fetch):

```javascript
const request = new Request(
    /* URL */,
    {
        method: 'POST',
        headers: {'X-CSRFToken': csrftoken},
        mode: 'same-origin' // Do not send CSRF token to another domain.
    }
);
fetch(request).then(function(response) {
    // ...
});
```

## Usando protección CSRF en plantillas de Jinja2

Django’s [`Jinja2`](/es/4.2/topics/templates/#django.template.backends.jinja2.Jinja2) template backend
adds `{{ csrf_input }}` to the context of all templates which is equivalent
to `{% csrf_token %}` in the Django template language. For example:

```html+jinja
<form method="post">{{ csrf_input }}
```

## Usando el método decorador

Rather than adding `CsrfViewMiddleware` as a blanket protection, you can use
the [`csrf_protect()`](/es/4.2/ref/csrf/#django.views.decorators.csrf.csrf_protect) decorator, which has
exactly the same functionality, on particular 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).

Use of the decorator by itself is **not recommended**, 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.

## Manejo de solicitudes rechazadas

By default, a “403 Forbidden” response is sent to the user if an incoming
request fails the checks performed by `CsrfViewMiddleware`. This should
usually only be seen when there is a genuine Cross Site Request Forgery, or
when, due to a programming error, the CSRF token has not been included with a
POST form.

The error page, however, is not very friendly, so you may want to provide your
own view for handling this condition. To do this, set the
[`CSRF_FAILURE_VIEW`](/es/4.2/ref/settings/#std-setting-CSRF_FAILURE_VIEW) setting.

CSRF failures are logged as warnings to the [django.security.csrf](/es/4.2/ref/logging/#django-security-logger) logger.

## Uso de la protección CSRF con almacenamiento en caché

If the [`csrf_token`](/es/4.2/ref/templates/builtins/#std-templatetag-csrf_token) template tag is used by a template (or the
`get_token` function is called some other way), `CsrfViewMiddleware` will
add a cookie and a `Vary: Cookie` header to the response. This means that the
middleware will play well with the cache middleware if it is used as instructed
(`UpdateCacheMiddleware` goes before all other middleware).

However, if you use cache decorators on individual views, the CSRF middleware
will not yet have been able to set the Vary header or the CSRF cookie, and the
response will be cached without either one. In this case, on any views that
will require a CSRF token to be inserted you should use the
[`django.views.decorators.csrf.csrf_protect()`](/es/4.2/ref/csrf/#django.views.decorators.csrf.csrf_protect) decorator first:

```
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect

@cache_page(60 * 15)
@csrf_protect
def my_view(request):
    ...
```

If you are using class-based views, you can refer to [Decorating
class-based views](/es/4.2/topics/class-based-views/intro/#id1).

## Pruebas y protección CSRF

The `CsrfViewMiddleware` will usually be a big hindrance to testing view
functions, due to the need for the CSRF token which must be sent with every POST
request. For this reason, Django’s HTTP client for tests has been modified to
set a flag on requests which relaxes the middleware and the `csrf_protect`
decorator so that they no longer rejects requests. In every other respect
(e.g. sending cookies etc.), they behave the same.

If, for some reason, you *want* the test client to perform CSRF
checks, you can create an instance of the test client that enforces
CSRF checks:

```pycon
>>> from django.test import Client
>>> csrf_client = Client(enforce_csrf_checks=True)
```

## Edge cases

Certain views can have unusual requirements that mean they don’t fit the normal
pattern envisaged here. A number of utilities can be useful in these
situations. The scenarios they might be needed in are described in the following
section.

### Deshabilitar la protección CSRF solo para algunas vistas

La mayoría de las vistas requieren protección CSRF, pero algunas no.

Solution: rather than disabling the middleware and applying `csrf_protect` to
all the views that need it, enable the middleware and use
[`csrf_exempt()`](/es/4.2/ref/csrf/#django.views.decorators.csrf.csrf_exempt).

### Setting the token when `CsrfViewMiddleware.process_view()` is not used

There are cases when `CsrfViewMiddleware.process_view` may not have run
before your view is run - 404 and 500 handlers, for example - but you still
need the CSRF token in a form.

Solution: use [`requires_csrf_token()`](/es/4.2/ref/csrf/#django.views.decorators.csrf.requires_csrf_token)

### Including the CSRF token in an unprotected view

There may be some views that are unprotected and have been exempted by
`csrf_exempt`, but still need to include the CSRF token.

Solution: use [`csrf_exempt()`](/es/4.2/ref/csrf/#django.views.decorators.csrf.csrf_exempt) followed by
[`requires_csrf_token()`](/es/4.2/ref/csrf/#django.views.decorators.csrf.requires_csrf_token). (i.e. `requires_csrf_token`
should be the innermost decorator).

### Protecting a view for only one path

A view needs CSRF protection under one set of conditions only, and mustn’t have
it for the rest of the time.

Solution: use [`csrf_exempt()`](/es/4.2/ref/csrf/#django.views.decorators.csrf.csrf_exempt) for the whole
view function, and [`csrf_protect()`](/es/4.2/ref/csrf/#django.views.decorators.csrf.csrf_protect) for the
path within it that needs protection. Example:

```
from django.views.decorators.csrf import csrf_exempt, csrf_protect

@csrf_exempt
def my_view(request):
    @csrf_protect
    def protected_path(request):
        do_something()

    if some_condition():
        return protected_path(request)
    else:
        do_something_else()
```

### Proteger una página que usa AJAX sin un formulario HTML

A page makes a POST request via AJAX, and the page does not have an HTML form
with a [`csrf_token`](/es/4.2/ref/templates/builtins/#std-templatetag-csrf_token) that would cause the required CSRF cookie to be sent.

Solution: use [`ensure_csrf_cookie()`](/es/4.2/ref/csrf/#django.views.decorators.csrf.ensure_csrf_cookie) on the
view that sends the page.

## CSRF protection in reusable applications

Because it is possible for the developer to turn off the `CsrfViewMiddleware`,
all relevant views in contrib apps use the `csrf_protect` decorator to ensure
the security of these applications against CSRF. It is recommended that the
developers of other reusable apps that want the same guarantees also use the
`csrf_protect` decorator on their views.
