Php 使用CSRF和Captha在Symfony中测试Ajax调用
我使用以下控制器方法渲染窗体:Php 使用CSRF和Captha在Symfony中测试Ajax调用,php,ajax,symfony,phpunit,symfony-3.4,Php,Ajax,Symfony,Phpunit,Symfony 3.4,我使用以下控制器方法渲染窗体: public function indexAction(Request $request) { $session=$this->get('session'); $builder = $this->get('app.captcha'); $builder->build(); $session->set('registration_step2',$builder-&g
public function indexAction(Request $request)
{
$session=$this->get('session');
$builder = $this->get('app.captcha');
$builder->build();
$session->set('registration_step2',$builder->getPhrase());
return $this->render('pages/registration.html.twig',[
'image'=>$this->createCaptcha('registration_step2')
])
}
我呈现的表单是pages/registration.html.twig
:
<form id="contactForm" class="col-12" data-scroll-to="displayRegistationPaperApplicationWrapper" action="{{ path('registration_email_contact') }}" method="post">
<input type="hidden" name="csrf" value="{{ csrf_token('insert-email') }}"/>
<div class="col-12 mb-3">
<div class="col-12">
<div class="input-group">
<div class="input-group-prepend">
<button class="btn btn-secondary" data-autofill-to="autofill_email" data-autofill-from="registrationEmail" id="emailAutofill">{{ 'register.step2.email.autofill'|trans }}</button>
</div>
<input id="autofill_email" type="email" name="autofill_email" class="form-control" placeholder="{{ 'register.step2.email'|trans }}" required/>
</div>
</div>
</div>
<div class="col-12">
<div class="col-2 float-left border">
<img id="capthaImage" class="img-fluid" data-captha-renew="registration_step2" src="{{ image }}">
</div>
<div class="col-10 float-right">
<div class="input-group">
<div class="input-group-prepend">
<button class="btn btn-secondary" id="reset-captcha">{{ 'register.captha.new-image'|trans }}</button>
</div>
<input type="text" name="captcha" class="form-control" placeholder="{{ 'register.captcha'|trans }}" required/>
</div>
</div>
</div>
<div class="col-12 mt-5 mb-2">
<div class="col-12 col-sm-12 col-md-5 col-lg-5 ml-auto">
<div class="btn-group" role="group" aria-label="Basic example">
<button id="rejectEmail" data-scroll-to="displayRegistationPaperApplicationWrapper" type="button" class="btn btn-link text-danger">{{ 'register.step2.no'|trans }}</button>
<button type="submit" class="btn btn-success">{{ 'register.step2.yes'|trans }}</button>
</div>
</div>
</div>
</form>
我想首先通过phpunit功能测试测试ajax提交的正常行为,但我将如何获得:
*当前csrf令牌
*Captha字符串
无需完整呈现放置csrf令牌和验证码的页面(因为它是多重表单的一部分)
对于验证码,我使用实现,并通过以下方式将其定义为服务:
app.captcha:
class: 'Gregwar\Captcha\CaptchaBuilder'
public: true
(我不使用该捆绑包,因为我发现在我使用Ajax的情况下它不方便。我计划立即重构我自己的服务。)为什么不使用Symfony表单?因为:*我通过Ajax而不是传统表单提交它们。*表单将不会被重用。
app.captcha:
class: 'Gregwar\Captcha\CaptchaBuilder'
public: true