-
-
Notifications
You must be signed in to change notification settings - Fork 8
Token stores
TokenStore is the base abstraction in this package. It's responsible for four things:
- generating token strings
- saving tokens so they become valid
- verifying that a submitted token is still valid
- spending tokens after successful use
The abstract class GT\Csrf\TokenStore provides:
generateNewToken()setTokenLength(int $length)getMaxTokens()verify(array|object $postData)
It leaves these methods for concrete stores to implement:
saveToken(string $token)verifyToken(string $token)consumeToken(string $token)
By default, tokens are generated as prefixed ULIDs, so the string begins with CSRF_ followed by a 32 character ULID.
$token = $tokenStore->generateNewToken();
echo $token; // CSRF_01H...If needed, we can change the length before generating tokens:
$tokenStore->setTokenLength(64);This changes the ULID portion of the token. The CSRF_ prefix remains in place.
That means the full token string length is always:
configured token length + strlen("CSRF_")
TokenStore keeps a maximum token count. By default this is 1000.
$tokenStore = new ArrayTokenStore(50);
echo $tokenStore->getMaxTokens(); // 50When more tokens are saved than the configured limit, the oldest stored token is discarded.
ArrayTokenStore stores tokens in a PHP array held in memory.
use GT\Csrf\ArrayTokenStore;
$tokenStore = new ArrayTokenStore();This is useful for:
- unit tests
- short-lived scripts
- custom applications where another layer persists the object for us
On its own, ArrayTokenStore does not survive between HTTP requests, so it is usually not enough for a normal browser form workflow unless we place the object somewhere persistent ourselves.
SessionTokenStore reads and writes the token list from a Gt\Session\SessionContainer.
use GT\Csrf\SessionTokenStore;
use Gt\Session\SessionArrayWrapper;
session_start();
$session = new SessionArrayWrapper($_SESSION);
$tokenStore = new SessionTokenStore($session);This is the usual choice for web applications because:
- the token generated when rendering a page is still available on the next request
- spent tokens can be tracked between requests
- the same store can be shared across the whole user session
Internally, the token list is saved under the session key tokenList.
Both built-in stores keep values in the same shape:
-
nullmeans the token exists and has not yet been used - an integer timestamp means the token has already been spent
That timestamp is later used by CsrfTokenSpentException to report when the token was previously consumed.
- Use
SessionTokenStorefor ordinary browser-based forms. - Use
ArrayTokenStorefor tests or temporary in-memory usage. - Extend
TokenStoreif your application needs a database, cache or other storage backend.
To see how tokens are inserted into HTML documents, read Protecting pages