在 access_control 规则重定向后通知用户的最佳方式是什么? [英] What is the best way to notify a user after an access_control rule redirects?

查看:19
本文介绍了在 access_control 规则重定向后通知用户的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Symfony 2.3 安全性文档:

<块引用>

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

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

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

为了澄清起见,我特别询问如何检查重定向是否是由 access_control 规则引起的(如果可能,最好在 twig 中).

解决方案

所以经过大量研究后,我找到了正确的方法.您需要使用入口点服务并在您的防火墙配置中定义它.

此方法不会弄乱您的默认页面 防火墙配置中指定的登录设置.


代码

security.yml:

防火墙:主要的:entry_point: entry_point.user_login #或任何你命名的服务模式:^/表单登录:# ...

src/Acme/UserBundle/config/services.yml

服务:entry_point.user_login:类:AcmeUserBundleServiceLoginEntryPoint参数:[@router] #我将使用它来生成 URL,因为我将在我的服务中重定向

src/Acme/UserBundle/Service/LoginEntryPoint.php:

命名空间 AcmeUserBundleService;使用 SymfonyComponentSecurityHttpEntryPointAuthenticationEntryPointInterface,SymfonyComponentSecurityCoreExceptionAuthenticationException,SymfonyComponentHttpFoundationRequest,SymfonyComponentHttpFoundationRedirectResponse;/*** 当用户根本没有经过身份验证时(即安全上下文还没有令牌时),* 将调用防火墙的入口点来启动()身份验证过程.*/类 LoginEntryPoint 实现了 AuthenticationEntryPointInterface{受保护的 $router;公共函数 __construct($router){$this->router = $router;}/** 该方法接收当前的Request对象和异常所产生的异常* 监听器被触发.** 该方法应该返回一个 Response 对象*/公共函数开始(请求 $request,AuthenticationException $authException = null){$session = $request->getSession();//我选择使用我自己的自定义消息设置 FlashBag 消息.//或者,您可以使用 AuthenticationException 的通用消息//通过调用 $authException->getMessage()$session->getFlashBag()->add('warning', '您必须登录才能访问该页面');return new RedirectResponse($this->router->generate('login'));}}

login.html.twig:

{# bootstrap 已准备好为您提供方便 ;] #}{% if app.session.flashbag.has('warning') %}{% for flashMessage in app.session.flashbag.get('warning') %}<div class="alert alert-warning"><按钮类型=按钮"类=关闭"data-dismiss=alert">&times;</button>{{ flashMessage }}

{% 结束为 %}{% 万一 %}

资源:

From Symfony 2.3 Security docs:

If access is denied, the system will try to authenticate the user if not already (e.g. redirect the user to the login page). If the user is already logged in, the 403 "access denied" error page will be shown. See How to customize Error Pages for more information.

I am currently using an access_control rule for a few routes. I would like to notify an anonymous user if they're redirected to the login route with a message like "You must login to access that page." I have read through the Security docs a few times and haven't found anything relevant to this. Am I overlooking something?

If not, what would be the best way to notify the user when they're stopped by an access_control rule only if they're redirected to login (ie not if they're just in an unauthorized role)?

EDIT: For clarification, I am specifically asking how to check if a redirect was caused by an access_control rule (preferably in twig if possible).

解决方案

So after quite a bit of research, I found the right way to do this. You'll need to use an Entry Point service and define it in your firewall configuration.

This method will not mess with your default page settings specified in your firewall config for logging in.


The Code

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: AcmeUserBundleServiceLoginEntryPoint
        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 AcmeUserBundleService;

use SymfonyComponentSecurityHttpEntryPointAuthenticationEntryPointInterface,
    SymfonyComponentSecurityCoreExceptionAuthenticationException,
    SymfonyComponentHttpFoundationRequest,
    SymfonyComponentHttpFoundationRedirectResponse;

/**
 * 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">&times;</button>
            {{ flashMessage }}
        </div>
    {% endfor %}
{% endif %}

Resources:

这篇关于在 access_control 规则重定向后通知用户的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆