paragonie / anti-csrf

Full-Featured Anti-CSRF Library
https://paragonie.com/projects
GNU Affero General Public License v3.0
297 stars 52 forks source link

Use with Ajax #30

Open interwap opened 6 years ago

interwap commented 6 years ago

Thanks for your awesome library works great with forms but not well with Ajax request and here's what i mean. An example has been sighted https://github.com/paragonie/anti-csrf/issues/15

If i had an ajax form, on submit... it validates ok and that token is expired from the session etc. But what if the user had entered the wrong information and i needed to submit again with refresh. This becomes a problem. I was able to fix this situation for myself by doing this;

function validateRequest( boolean $is_async = false ) .......... if ( ! $is_async ) { if ($this->deleteToken($sess[$index])) { unset($sess[$index]); } }

Now, if my endpoint is access only via ajax i do $csrf->validateRequest( true );

This way, it doesn't expire the token and index. But when i refresh the form manually, i first unset( $_SESSION['CSRF'] so a new hidden token and index is created.

Is this worth adding to the core, for other users?

paragonie-scott commented 6 years ago

The AntiCSRF class was never designed for AJAX forms. Each CSRF token is meant to be single-use to prevent replay attacks.

However, the Reusable variant should work fine.

tvirelli commented 1 year ago

Pardon my ignorance on this, but how would I implement the Reusable version?

paragonie-security commented 1 year ago

First, consider the canonical example from the README:

use \ParagonIE\AntiCSRF\AntiCSRF;
$twigEnv->addFunction(
    new \Twig\TwigFunction(
        'form_token',
        function($lock_to = null) {
            static $csrf;
            if ($csrf === null) {
                $csrf = new AntiCSRF;
            }
            return $csrf->insertToken($lock_to, false);
        },
        ['is_safe' => ['html']]
    )
);

You just want to change the class definition if the static $csrf is null.

            static $csrf;
            if ($csrf === null) {
-               $csrf = new AntiCSRF;
+               $csrf = new Reusable;
            }

(You also want to add another use statement at the top to import this class.)

Since Reusable extends the AntiCSRF class, you can just change your code to use that instead.

If you want to reconfigure it:

            static $csrf;
            if ($csrf === null) {
-               $csrf = new AntiCSRF;
+               $csrf = (new Reusable())
+                  ->reconfigure([
+                      'tokenLifetime' => new \DateInterval('PT01H'), // 1 hour
+                  ]);
            }