class Security_Csrf

Security_Csrf class handles creation and validation of tokens aimed at anti-CSRF protection.

/**
* CSRF Security class
* @author Kirill Egorov
* @package Security
* @uses Utils, Store_Interface , Store_Session , Request
*/

class Security_Csrf

{

// a constant value, the name of the header parameter carrying the token

const HEADER_VAR = 'HTTP_X_CSRF_TOKEN';

// a constant value, the name of the token parameter being passed by POST request

const POST_VAR = 'xscrftoken';

/**
* Set token storage implementing the Store_interface
* @param Store $store
*/

static public function setStorage(Store_Interface $store)

/**
* Set config options (storage, lifetime, cleanupLimit)
* @param array $options
* @throws Exception
*/

static public function setOptions(array $options)

/**
* Create and store token
* @return string
*/

public function createToken()

/**
* Check if token is valid
* @param string $token
* @return boolean
*/

public function isValidToken($token)

/**
* Remove tokens with expired lifetime
*/

public function cleanup()

/**
* Invalidate (remove) token
* @param string $token
*/

public function removeToken($token)

/**
* Check POST request for a token
* @param string $tokenVar - Variable name in the request
* @return boolean
*/

public function checkPost($tokenVar = Security_Csrf::POST_VAR)

/**
* Check HEADER for a token
* @param string $tokenVar - Variable name in the header
* @return boolean
*/

public function checkHeader($tokenVar = Security_Csrf::HEADER_VAR)

}

A simple example of checking for a token:


$csrf = new Security_Csrf();

/*
* Set token options
* lifetime — 1 hour of lifetime
* cleanupLimit — the limit of stored tokens. Being reached, 
* it starts cleanup of obsolete tokens (of the current user)
* storage — the storage of tokens, a session by default leave it as is.
*/

$csrf->setOptions(
		array(
			'lifetime' => 3600,
			'cleanupLimit' => 300
			)
	);
	
// Check data headers in POST requests (AJAX requests in this case) for a token
if(!$csrf->checkHeader() && !$csrf->checkPost())
Response::jsonError('Error Message');

comments powered by Disqus