Я использовал Gregwar/CaptchaBundle
вот так:
namespace AppBundle\Security\Captcha;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Templating\EngineInterface;
use Gregwar\CaptchaBundle\Generator\CaptchaGenerator as BaseCaptchaGenerator;
class CaptchaGenerator
{
/**
* @var EngineInterface
*/
private $templating;
/**
* @var BaseCaptchaGenerator
*/
private $generator;
/**
* @var Session
*/
private $session;
/**
* @var string
*/
private $sessionKey;
/**
* @var array
*/
private $options;
public function __construct(EngineInterface $templating, BaseCaptchaGenerator $generator, SessionInterface $session, $sessionKey, array $options)
{
$this->templating = $templating;
$this->generator = $generator;
$this->session = $session;
$this->sessionKey = $sessionKey;
$this->options = $options;
}
/**
* @return string
*/
public function generate()
{
$options = $this->options;
$code = $this->generator->getCaptchaCode($options);
$this->session->set($this->sessionKey, $options['phrase']);
return $this->templating->render('AppBundle:My/Security:captcha.html.twig', array(
'code' => $code,
'width' => $options['width'],
'height' => $options['height'],
));
}
}
namespace AppBundle\Security\Captcha;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class CaptchaValidator
{
/**
* @var Session
*/
private $session;
/**
* @var string
*/
private $sessionKey;
public function __construct(SessionInterface $session, $sessionKey)
{
$this->session = $session;
$this->sessionKey = $sessionKey;
}
/**
* @param string $value
* @return bool
*/
public function validate($value)
{
return $this->session->get($this->sessionKey, null) === $value;
}
}
{# AppBundle:My/Security:captcha.html.twig #}
<img class="captcha_image" src="{{ code }}" alt="" title="captcha" width="{{ width }}" height="{{ height }}" />
# services.yaml
parameters:
app.security.captcha.security_key: captcha
services:
AppBundle\Security\Captcha\CaptchaGenerator:
lazy: true
arguments:
$sessionKey: '%app.security.captcha.security_key%'
$options: '%gregwar_captcha.config%'
AppBundle\Security\Captcha\CaptchaValidator:
arguments:
$sessionKey: '%app.security.captcha.security_key%'
, затем подтвердите значение в AppBundle\Security\FormAuthenticator
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
{
if (!$this->captchaValidator->validate($token->getCaptchaValue())) {
throw new CustomUserMessageAuthenticationException('security.captcha');
}
// ...
}