How do I prevent Asp.NET PWA anti-forgery token being cached?

640 views Asked by At

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!

0

There are 0 answers