-
-
Notifications
You must be signed in to change notification settings - Fork 8
Exceptions
This repository uses exceptions to report CSRF verification failures. All package-specific exceptions extend GT\Csrf\Exception\CsrfException.
CsrfExceptionCsrfTokenMissingExceptionCsrfTokenInvalidExceptionCsrfTokenSpentException
That means we can either catch specific cases or catch the base class.
This is thrown when submitted data exists but there is no csrf-token field at all.
Typical causes:
- the form was rendered without calling
protect() - a client script submitted partial form data and omitted the token
- a request was forged manually
This is thrown when a token is present in the request, but it is not known to the current token store.
Typical causes:
- the token was never generated by this application instance
- the token has been evicted because the store exceeded its maximum token count
- the request belongs to a different session or environment
This is thrown when the token exists but has already been used.
The exception message includes the earlier use time in ISO 8601 format, because the store records the consumption timestamp when consumeToken() is called.
Typical causes:
- the form was submitted twice
- background requests reused an old token
- the browser re-sent stale form data after a previous successful submission
Catch the base exception when all failures should be handled in the same way:
use GT\Csrf\Exception\CsrfException;
try {
$tokenStore->verify($_POST);
}
catch(CsrfException $exception) {
http_response_code(403);
echo $exception->getMessage();
}Catch specific subclasses when you want to distinguish the response:
use GT\Csrf\Exception\CsrfTokenMissingException;
use GT\Csrf\Exception\CsrfTokenSpentException;
try {
$tokenStore->verify($_POST);
}
catch(CsrfTokenMissingException $exception) {
http_response_code(400);
}
catch(CsrfTokenSpentException $exception) {
http_response_code(409);
}The package itself does not decide what HTTP response to send. It only reports the verification result.
If tokens should be stored somewhere other than memory or the session, read Custom stores.