# README
csrf
Generate CSRF (cross-site request forgery) tokens and validate them.
Concept
Unlike most CSRF implementations, this package does not rely on remembering previously handed out tokens. Instead, it uses TOTP (time-based one-time password) to generate an almost limitless number of CSRF tokens, and can validate them without needing to store a collection of active tokens.
This results in fewer false failures. For example, if a user keeps a form page open for a long time before submitting it, or performs other actions in another tab before submitting, the form submission will still succeed and still be protected against CSRF attacks. These patterns of behavior would cause other CSRF implementations to forget about the token, resulting in an unnecessary failure.
There are two downsides to this approach. The tokens must be twice as long to provide the same protection against brute-force attacks, because so many more of the randomly generated tokens are valid. Also, tokens cannot be revoked after being used once.
Usage
When you generate a token, you pass the current time (from time.Now()) and a byte slice that uniquely identifies the user. This can be as simple as []byte(username) or if you have a session token you can use that. Include this token in your HTML page as a hidden form field.
When you validate a token, it will validate if and only if the session matches and the token lifetime has not expired. This ensures the request being made is from the HTML page you generated earlier, and not from a malicious script or link on the user's device.
The tokens generated by this package are strings using alphanumeric characters, plus dot, dash, underscore, and tilde. These characters are safe to use in URL query strings, HTML attributes, and cookies.
License
This package is released under the GPL, version 2. If you require a different license, please contact me for permission.