你想要实现一个登录表单吗?这个例子告诉你。很容易的。这一路上,你会学会所有认证过程中发生的每一步,以及如何自定义这些步骤。
你还需要做一些事情,但你会很高兴做这些事。
创建登录表单
不用去想关于安全的事情了!我们通过一个symfony控制器中的两个action方法入手:一个用来渲染表单,一个用来处理登录提交:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
//src/AppBundle/Controller/SecurityController.php <?php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class SecurityController extends Controller { /** * @Route("/login", name="security_login") */ public function loginAction() { $helper = $this->get('security.authentication_utils'); return $this->render('security/login.html.twig', array( // last username entered by the user (if any) 'last_username' => $helper->getLastUsername(), // last authentication error (if any) 'error' => $helper->getLastAuthenticationError(), )); } /** * @Route("/login_check", name="security_login_check") */ public function loginCheckAction() { // will never be executed } } |
目前为止,这是一个喜欢,又枯燥的一套动作。唯一有趣的部分就是last_username和error变量了。你会问这些来自哪里?后面你会看到的。此外loginCheckAction()不会做什么事情,永远不会。其他地方(另一个层面)会处理登录提交的。
下一步,创建登录模板:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<!--app/Resources/views/security/login.html.twig--> {% extends 'base.html.twig' %} {% block body %} <form action="{{ path('security_login_check') }}" method="post"> {% if error %} <div class="alert alert-danger"> {{ error.messageKey|trans(error.messageData) }} </div> {% endif %} <div> <label for="username">Username</label> <input type="text" id="username" name="_username" value="{{ last_username }}" /> </div> <div> <label for="password">Password:</label> <input type="password" id="password" name="_password" /> </div> <br/> <button type="submit">Login</button> </form> {% endblock %} |
这个表单提交_username
和 _password到/login_check (URL)。记住这些-他们很重要会在一分钟之后使用(在getCredentials())
安装Guard
阅读 symfony Authentication Guard 一 安装 ,确保您已经安装了bundle并开启。
创建一个验证(Authenticator)
使用Guard,来完成整个验证过程-获取POST过来的用户名/密码值,验证密码,跳转到成功页面,等(还有处理调用”Authenticator”的类)。你的验证可以很疯狂,只要他实现了KnpU\Guard\GuardAuthenticatorInterface.
未完待续。。。。。