How to manage CRSV token manually in Symfony?
I am trying to use CRSF token management without FormType. So in my branch template, I just use this to create a token:
{{ csrf_token( inception_inscription ) }}
In a controller, I am trying to do this:
$tokenManager = $this->get('security.csrf.token_manager');
$token = $request->get('token');
inception = $this->container->getParameter('crsf_inscription_inception');
if (!$tokenManager->isTokenValid($tokenManager->getToken($inception, $token))) {
throw new HttpException(400, 'Invalid token');
}
But in reality, the isTokenValid method always returns true. I can make the $ token vaiable what I want, it will never be false, so no validation is needed.
When I debug step by step, I look at Symfony \ Component \ Security \ Csrf :: getToken () and this method checks: ($ this-> storage-> hasToken ($ tokenId)) which always return false and force the process generate a new token.
I really don't understand how it works. Here is some ore information about my code: Symfony 2.6.x
framework:
secret: "%secret%"
router:
resource: "%kernel.root_dir%/config/routing.yml"
strict_requirements: ~
form:
csrf_protection:
enabled: true
field_name: token_my
csrf_protection:
enabled: true
validation: { enable_annotations: true }
templating:
engines: ['twig']
#assets_version: SomeVersionScheme
default_locale: "%locale%"
trusted_hosts: ~
trusted_proxies: ~
session:
handler_id: ~
name: 'my'
fragments: ~
http_method_override: true
# Twig Configuration
twig:
debug: "%kernel.debug%"
strict_variables: "%kernel.debug%"
globals:
inception_inscription: %crsf_inscription_inception%
source to share
From what I understand, $ tokenManager-> getToken ($ tokenId) always generates a new, valid token. You are probably most likely to check the provided token, for example:
$tokenManager = $this->get('security.csrf.token_manager');
$tokenId = $this->container->getParameter('crsf_inscription_inception');
$tokenValue = $request->get('token');
$token = new CsrfToken($tokenId, $tokenValue);
if (!$tokenManager->isTokenValid($token)) {
throw new HttpException(400, 'Invalid token');
}
source to share