Can you explain how the Synchronizer Token Pattern works for CSRF protection?

The Synchronizer Token Pattern (STP) is a CSRF protection method that uses unique tokens embedded within web forms. When a user logs in, the server generates a cryptographically strong token tied to the user’s session. This token is then inserted into every form served to the client. Upon receiving a request, the server verifies if the token matches the one associated with the user’s session. If they match, the request is legitimate; otherwise, it’s considered a CSRF attack and rejected. The STP relies on the fact that an attacker cannot predict or access these tokens due to same-origin policy restrictions.