从Symfony2.3安全文档:
如果访问被拒绝, 则系统将尝试对用户进行身份验证(如果尚未进行身份验证)(例如,将用户重定向到登录页面) 。如果用户已经登录,将显示403“访问被拒绝”错误页面。有关更多信息,请参见如何自定义错误页面。
我目前access_control在一条路线上使用一条规则。如果匿名用户被重定向到登录路由,我想通过一条消息“ 您必须登录才能访问该页面 ” 来通知他们。我已经阅读了几次安全性文档,但没有发现与此相关的任何内容。我在俯视什么吗?
access_control
如果不是,那么 仅* 当用户被重定向到登录时(即,如果他们只是 未经授权的角色 就不会), 才有 一条最好的方式通知用户何时被access_control规则停止? * __
编辑: 为澄清起见,我专门问如何检查重定向是否是由access_control规则引起的(如果可能,最好在树枝中)。
因此,经过大量研究,我找到了正确的方法。您需要使用入口点服务,并在防火墙配置中对其进行定义。
此方法 不会 与您在防火墙配置中指定的用于登录的默认页面设置混淆。
security.yml:
firewalls: main: entry_point: entry_point.user_login #or whatever you name your service pattern: ^/ form_login: # ...
src / Acme / UserBundle / config / services.yml
services: entry_point.user_login: class: Acme\UserBundle\Service\LoginEntryPoint arguments: [ @router ] #I am going to use this for URL generation since I will be redirecting in my service
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; /** * When the user is not authenticated at all (i.e. when the security context has no token yet), * the firewall's entry point will be called to start() the authentication process. */ class LoginEntryPoint implements AuthenticationEntryPointInterface { protected $router; public function __construct($router) { $this->router = $router; } /* * This method receives the current Request object and the exception by which the exception * listener was triggered. * * The method should return a Response object */ public function start(Request $request, AuthenticationException $authException = null) { $session = $request->getSession(); // I am choosing to set a FlashBag message with my own custom message. // Alternatively, you could use AuthenticationException's generic message // by calling $authException->getMessage() $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 %}