简体   繁体   中英

Set custom CsrfTokenGenerator in Symfony 3.4

I'm constructing an example in Symfony 3.4 that showcases how not to generate CSRF tokens (for educational purposes). I've made a custom CsrfTokenGenerator that implements the TokenGeneratorInterface , but now I would like to configure the CsrfTokenManager that's built-in in Symfony to use this generator for generating CSRF-tokens instead of the default one. How can I configure this in the Symfony yml-files? Or is there any other way to achieve this?

The CsrfTokenManager constructor has the following signature public function __construct(TokenGeneratorInterface $generator = null, TokenStorageInterface $storage = null, $namespace = null) and can thus take a custom TokenGeneratorInterface as a parameter, but how can I set this parameter, as we don't have direct access to this controller.

Uhh, this is a good one. There's no simple way of doing it. By simple way I mean overriding a config parameter.

In situations like these you make use of Compiler Passes . Here is the way to go about it:

  1. Register your implementation of TokenGeneratorInterface as a service.
  2. Then, create and register a compiler pass. You can name it CustomCsrfTokenGeneratorPass . There are different ways of registering it depending if you are in a bundle or in your app.
  3. In that compiler pass, you have access to the container builder. Use the $container->findDefinition() method to find the registered definition of the CsrfTokenManager .
  4. Then modify the service definition by calling $definition->setArgument() on it. Replace the argument of your choice with a reference. `new Reference('your-custom-crsf-token-generator-service-id').
  5. Enjoy.

Make sure to take a look to the compiler pass docs for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM