Not sure I agree with the premise that checking referer and origin headers is the best defence. In a few corner cases both of these headers will be missing. In these cases the only safe option is to block the request, which could break functionality for a few legitimate users.
If this is still the path you want to take, OWASP has a lot of good info on the technicalities:
- Start with the origin header, and if it is missing use the referer header.
- Again, if none of these are present, you must block.
- Comparing URL:s might seem simple, but it is actually a very tricky thing to do. Make sure your comparison is sound, and e.g. that
good.com.evil.com does not pass as
good.com. That is just an example, I am sure there are more pitfalls out there. Preferably you should use a good well tested library for this task.
- It's probably good to check that the scheme is either
https://. Not sure if there are any attacks that can be used if this check is not done, but god knows what clever tricks there are out there with data URI:s or what not.
If you want other options, consider the classics such as anti-CSRF tokens or double submit cookies. Or for an API, just using a bearer token in the authentication header does the trick.