实现AccessDeniedHandlerInterface以捕获任何AccessDeniedExceptions时,是否可以访问用户角色以确定适当的RedirectResponse路由?
我想将未登录的用户定位到一个地方,以及登录但没有权限到另一个地方的人,而不是仅仅获取403页。
答案 0 :(得分:2)
该问题的一个解决方案是将SecurityContext对象作为参数传递给AccessDeniedHandlerInterface
文件中的config.yml
,如此。
//config.yml
kernel.listener.access_denied_listener:
class: Path\To\Your\Class
arguments: [@security.context]
tags:
- { name: kernel.event_listener, event: kernel.exception, method: handle }
这样做允许handle()
方法访问代表当前用户身份验证的令牌。由此可以进行适当的重新路由。
namespace Path\To\Your\Class;
use Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Request;
class AccessDeniedListener implements AccessDeniedHandlerInterface
{
protected $security;
public function __construct(SecurityContext $security)
{
$this->security = $security;
}
public function handle(Request $request, AccessDeniedException $accessDeniedException)
{
if ($this->security->isGranted('ROLE_USER')) {
return new RedirectResponse('user_route');
}
}
}