0

I have a progressive web application which uses sw-toolbox to manage caching of resources.

The log in page (/user/login?returnurl=xxxx) requires an anti-forgery token, so I configured the sw-toolbox router like this to ensure a cached version of the page contents aren't returned:

toolbox.router.any("/user/*", toolbox.networkOnlyCustom);

where the networkOnlyCustom method uses the networkOnly built in method with a caveat to return a cached "sorry, you're offline" page if the user is offline (see below):

toolbox.networkOnlyCustom = function (req, vals, opts) {
    return toolbox.networkOnly(req, vals, opts)
        .catch(function (error) {
            if (req.method === "GET" && req.headers.get("accept").includes("text/html"))
                return toolbox.cacheOnly(new Request("/home/offline"), vals, opts);
            throw error;
        });
};

However, what Im seeing is the "The anti-forgery cookie token and form field token do not match" error appearing a lot. Not all the time though! In fact, if the user sees that error, then clicks "Back" on the browser and submits the form again, they log in just fine.

I assumed the reason for this is that the browser (Chrome 71 in my case) is caching the log in page. So I added the following HTTP response headers in the hope the browser would obey:

cache-control: no-cache, no-store, no-store, must-revalidate
expires: -1
pragma: no-cache

However, this hasnt fixed my problem. Any ideas would be most appreciated!

Jimbo
  • 22,379
  • 42
  • 117
  • 159
  • Kindly refer to this blog [Prevent Cross-Site Request Forgery (CSRF) using ASP.NET MVC’s AntiForgeryToken() helper](http://blog.stevensanderson.com/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/). – Jessica Rodriguez Jan 31 '19 at 11:31
  • I am using anti-forgery tokens, thats where the issue arrives, because the page content including the old anti-forgery token (in the form's __RequestVerificationToken field) is being cached and re-used for subsequent log in attempts which results in the "anti-forgery cookie token and form field token do not match" error – Jimbo Feb 01 '19 at 07:24
  • I may update this answer soon. The antiforgery token was really created to make it hard to hack a site using HTTP. Service workers require HTTPS. Therefore it is better to use OAuth tokens and add them to the request Authorization header. I have been trying to find a way to cache MVC Views (the HTML) for a few days now. The cookie auth stuff is just so out of date. I think it is better to update to a modern authentication protocol for so many reasons. – Chris Love May 27 '20 at 21:57
  • Using HTTPS doesn't prevent a CSRF attack. – Dejan Oct 01 '20 at 09:09
  • @ChrisLove Did you have a solution to this? I'm just starting on PWA and ran in to this bugger. It seems the servicehelper somehow forces a new token but the page itself uses the old one. – Henrik Clausen Apr 07 '21 at 14:53

0 Answers0