在access_control规则重定向后通知用户的最佳方法是什么?

Car*_*all 20 php redirect access-control symfony twig

来自Symfony 2.3安全文档:

如果拒绝访问,系统将尝试验证用户(如果尚未验证)(例如,将用户重定向到登录页面).如果用户已登录,将显示403"访问被拒绝"错误页面.有关更多信息,请参见如何自定义错误页面.

我目前正在使用access_control几条路线的规则.我想通知匿名用户,如果他们被重定向到登录路线,并显示" 您必须登录才能访问该页面 " 的消息.我已经阅读了几次安全文档并且没有找到与此相关的任何内容.我忽略了什么吗?

如果没有,只有当他们被重定向到登录时(即不是他们只是未经授权的角色),当他们被access_control规则停止时通知用户的最佳方式是什么?

编辑: 为了澄清,我特别询问如何检查重定向是否是由access_control规则引起的(如果可能的话,最好是在树枝上).

Car*_*all 57

经过相当多的研究,我发现了正确的方法.您需要使用入口点服务并在防火墙配置中定义它.

这种方法不会弄乱你的默认页在您的防火墙配置为登录指定的设置.


代码

security.yml:

firewalls:
    main:
        entry_point: entry_point.user_login #or whatever you name your service
        pattern: ^/
        form_login:
        # ...
Run Code Online (Sandbox Code Playgroud)

SRC /阿克米/ UserBundle /配置/ 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
Run Code Online (Sandbox Code Playgroud)

SRC /阿克米/ UserBundle /服务/ 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'));
    }
}
Run Code Online (Sandbox Code Playgroud)

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">&times;</button>
            {{ flashMessage }}
        </div>
    {% endfor %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

资源:

  • 好一个嘉莉,真是个噩梦! (5认同)