经过一番研究,我找到了正确的方法。您需要使用入口点服务,并在防火墙配置中定义它。
这种方法不会影响您在防火墙配置中指定的默认页面设置以进行登录。
代码
security.yml:
firewalls:
main:
entry_point: entry_point.user_login
pattern: ^/
form_login:
src/Acme/UserBundle/config/services.yml
services:
entry_point.user_login:
class: Acme\UserBundle\Service\LoginEntryPoint
arguments: [ @router ]
src/Acme/UserBundle/Service/LoginEntryPoint.php:
namespace Acme\UserBundle\Service;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface,
Symfony\Component\Security\Core\Exception\AuthenticationException,
Symfony\Component\HttpFoundation\Request,
Symfony\Component\HttpFoundation\RedirectResponse;
class LoginEntryPoint implements AuthenticationEntryPointInterface
{
protected $router;
public function __construct($router)
{
$this->router = $router;
}
public function start(Request $request, AuthenticationException $authException = null)
{
$session = $request->getSession();
$session->getFlashBag()->add('warning', 'You must be logged in to access that page');
return new RedirectResponse($this->router->generate('login'));
}
}
login.html.twig:
{# bootstrap ready for your convenience ;] #}
{% if app.session.flashbag.has('warning') %}
{% for flashMessage in app.session.flashbag.get('warning') %}
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ flashMessage }}
</div>
{% endfor %}
{% endif %}
资源: