The simplest way to prevent CSRF is to use the Referer header, and that has been used since forever. If the header is missing, you no-op the post. Origin is similar, and can be used with referer as fallback, but it's not needed for most sites.
Your attempt has similarities to the idea behind Checking Sec-Fetch-Site. Implementing that header is the same amount of work. But this header is exactly meant for this purpose, and referer is haunted with problems.
So for officially intended protections, implementing this header and samesite cookies gets you a very long way without any complexity, assumptions, or tricks of old lore.
It's not a wrong solution. It's been commonly used since forever, tens of years before the sec-fetch-site header existed, and it stops CSRF. Sec-fetch-site is not supported in old browsers, so relying on that is unsafe without any fallbacks.
Fetch Metadata headers, as discussed in this post, are just as simple and much more effective. There's lots of issues with referer, and even some with origin.
talkin|2 months ago
Your attempt has similarities to the idea behind Checking Sec-Fetch-Site. Implementing that header is the same amount of work. But this header is exactly meant for this purpose, and referer is haunted with problems.
So for officially intended protections, implementing this header and samesite cookies gets you a very long way without any complexity, assumptions, or tricks of old lore.
NorwegianDude|2 months ago
nchmy|2 months ago
justarandomname|2 months ago