Symfony2的AccessDeniedHandlerInterface可自动重定向未经授权的用户 [英] Symfony2's AccessDeniedHandlerInterface to automatically redirect unauthorized users

查看:94
本文介绍了Symfony2的AccessDeniedHandlerInterface可自动重定向未经授权的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实现 AccessDeniedHandlerInterface 时,任何 AccessDeniedExceptions 是否可以访问角色以确定合适的RedirectResponse路由的用户?

When implementing an AccessDeniedHandlerInterface to catch any AccessDeniedExceptions is it possible to access the role of the user in order to determine an appropriate RedirectResponse route?

我想引导未登录的人和已登录但没有权限的人访问另一位置,而不是仅仅获得403页.

I want to direct people who aren't logged in to one place, and people that are logged in but don't have the permissions to another place, instead of just getting a 403 page.

推荐答案

该问题的一种解决方案是通过

One solution to the problem is to pass the SecurityContext object as an argument to the AccessDeniedHandlerInterface in the config.yml file like so.

//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()方法访问代表当前用户身份验证的令牌.由此可以进行适当的重新路由.

Doing this allows the handle() method access to the token representing the current user authentication. From this the appropriate re-routing can take place.

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');
        }
    }
}

这篇关于Symfony2的AccessDeniedHandlerInterface可自动重定向未经授权的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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