简体   繁体   中英

django 1.7 csrf_token not working: how is it supposed to work?

Page 1: Form with {% csrf_token %} in my template.

Page 2: Thanks page.

When I submit my form on Page 1 it uses HttpResponseRedirect to redirect to Page 2... so if the user refresh the page it will no be able to resubmit...

but I just noticed that if the user goes back in Page 2 to Page 1... He can press Submit button again an resubmit the same form... So... Is there a way to expire Page 1 when I show Page 2?

Just in case, my Middleware Classes are:

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

That's not what a CSRF token is meant to do, though technically you could regenerate the token and the user will see a 403 Forbidden response when he tries to resubmit. A CSRF token should be just that, though - a token that prevents cross-site request forgery.

If a user should only be able to submit a form once, that should be handled in the form validation and checked against the database. Otherwise, going back and resubmitting the form is often considered an explicit action by the user and is handled the same as submitting a new form.

CSRF token is designed to prevent other sites from posting content to your pages, thus prevent the creation of junk/spam records.

It is only designed for POST requests.

In order to prevent someone from writing a script that simply submits junk data to your pages, a unique token is generated using a secret key (which will not be known to the attacker).

On a legitimate request that comes from your site - your code generates a token using this key and sends it as part of the request.

The rogue request will not have this key, and your code will raise an appropriate error (thus preventing whatever action from taking place).

It is not designed to prevent legitimate, duplicate requests. There are two main ways to prevent this:

  1. Make sure you always redirect after POST (this is to prevent someone hitting refresh and then sending the same request again; although almost all modern browsers will warn when doing so).

  2. Control on the server side to prevent suspect duplicate entries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM