2013-10-14 59 views
2

我通過Symfony2 security documentation有此登錄窗體具有以下嫩枝模板內容:Symfony2中,登錄表單 - CSRF保護

<form action="{{ path('login_check') }}" method="post"> 
    <div class="input form"> 
     <label for="username">Account name or E-mail:</label> 
     <input type="text" id="username" name="_username" value="{{ last_username }}" required="required" /> 
    </div> 
    <div class="input form"> 
     <label for="password">Password:</label> 
     <input type="password" id="password" name="_password" required="required" /> 
    </div> 
    <input type="hidden" name="_token" value="{{ csrf_token("intention") }}"> 
    <button type="submit">Log In</button> 
</form> 

我想以這種形式添加CSRF保護。正如你所看到的,我添加了這條線<input type="hidden" name="_token" value="{{ csrf_token("intention") }}">,但我不確定,如果它足以激活這種保護。

我的控制器具有相同形式的文檔,所以它看起來是這樣的:

<?php 
// src/Acme/SecurityBundle/Controller/SecurityController.php; 
namespace Acme\SecurityBundle\Controller; 

use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
use Symfony\Component\Security\Core\SecurityContext; 

class SecurityController extends Controller 
{ 
    public function loginAction() 
    { 
     $request = $this->getRequest(); 
     $session = $request->getSession(); 

     // get the login error if there is one 
     if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) { 
      $error = $request->attributes->get(
       SecurityContext::AUTHENTICATION_ERROR 
      ); 
     } else { 
      $error = $session->get(SecurityContext::AUTHENTICATION_ERROR); 
      $session->remove(SecurityContext::AUTHENTICATION_ERROR); 
     } 

     return $this->render(
      'AcmeSecurityBundle:Security:login.html.twig', 
      array(
       // last username entered by the user 
       'last_username' => $session->get(SecurityContext::LAST_USERNAME), 
       'error'   => $error, 
      ) 
     ); 
    } 
} 

所以這是不夠的只是貼上與價值{{ csrf_token("intention") }}一個隱藏的輸入或我要補充的東西到控制器?

回答

2

我發現@Chris McKinnel的回答不正確。現在,Symfony2的有教程頁面上本節:

http://symfony.com/doc/current/cookbook/security/csrf_in_login_form.html

我需要添加一行在我security.yml

form_login: 
     # ... 
     csrf_provider: form.csrf_provider 

並更改該

<input type="hidden" name="_token" value="{{ csrf_token("intention") }}"> 

<input type="hidden" name="_csrf_token" value="{{ csrf_token("authenticate") }}"> 

現在我確定我的身份驗證表單CSRF受保護。

+0

你需要調用你的任何表單「form_login」嗎? – Sekai

+0

@Sekai它是用於識別登錄表單的配置項目。在這個項目中,您可以設置選項,例如登錄操作的路線,或者您也可以在此答案中看到csrf提供程序。 –

+0

是的,我同意,但我試圖操縱表單中的令牌(我添加了隨機字符)並提交了我的表單,並且它成功了。 保護是如何工作的? – Sekai

1

默認情況下啓用CSRF保護,因此您只需在您的HTML中呈現您的CSRF令牌。你不需要在你的控制器中做任何事情。

你有兩個選擇:

  1. 做它就像你已經做到了上述
  2. 使用{{ form_rest(form) }},這會使你還沒有渲染的所有領域,包括像隱藏字段CSRF令牌

兩者都可以正常工作。

+1

但是這個登錄沒有生成表單,所以我不能使用這個功能 –