gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-28 23:55:28 25 4
gpt4 key购买 nike

来自 Symfony 2.3 Security文档:

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.

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

如果不是,当用户被 access_control 规则 重定向到登录(即不如果他们只是未经授权的角色)?

编辑:为澄清起见,我特意询问如何检查重定向是否由 access_control 规则引起(如果可能,最好在 Twig 中)。

最佳答案

经过大量研究,我找到了执行此操作的正确方法。您需要使用 Entry Point服务并在您的防火墙配置中定义它。

此方法不会弄乱您的default page在您的防火墙配置中指定的用于登录的设置。


代码

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

资源:

关于php - 在 access_control 规则重定向后通知用户的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17428987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com