【问题标题】:Redirect user after verifying that he is connected with Symfony 4 and FOSUserBundle在验证用户与 Symfony 4 和 FOSUserBundle 连接后重定向用户
【发布时间】:2020-03-21 15:10:45
【问题描述】:

世界你好!
我是一名 laravel 开发人员,但有一段时间我一直在从事 symfony 项目。 在我的工作中,我刚刚遇到了一个主要问题,即在检查用户是否登录后运行一段代码。
在 laravel 上,我可以使用提供者、中间件或基本控制器来做到这一点。但是在 Symfony 4 上我被阻止了。
我使用方法$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
我希望每次我们检查我们可以运行这个方法:

if ($this->getUser()->getMetaValue('level') == "ADMIN") {
     $ip = file_get_contents("http://ipecho.net/plain");
     $record = $this->get('geoip2.reader')->city($ ip);
     $isoCode = $record->country->isoCode;
     if ($isoCode! = "USA") {
         return $this->render('backOffice/vpn_error.html.twig');
     }
}

因此,每次连接管理员时,我们都会检查它是否从美国连接,否则会被要求使用 VPN 来获得 IP 地址。 感谢您的关注。

【问题讨论】:

标签: php symfony redirect middleware fosuserbundle


【解决方案1】:

@Yoshi 谢谢! 我找到了解决方案,但我知道这不是最好的,但目前它让我满意。我已经编辑了denyAccessUnlessGranted() 方法,并使用 echo 强制显示错误 我的解决方案是这样的:

    /**
     * Throws an exception unless the attributes are granted against the current authentication token and optionally
     * supplied subject.
     *
     * @throws AccessDeniedException
     *
     * @final
     */
    protected function denyAccessUnlessGranted($attributes, $subject = null, string $message = 'Access Denied.')
    {
        if (!$this->isGranted($attributes, $subject)) {
            $exception = $this->createAccessDeniedException($message);
            $exception->setAttributes($attributes);
            $exception->setSubject($subject);

            throw $exception;
        } 
        if ($this->getUser()->getMetaValue('level') == "ADMIN") {
            $ip = file_get_contents("http://ipecho.net/plain");
            $record = $this->get('geoip2.reader')->city($ ip);
            $isoCode = $record->country->isoCode;
            if ($isoCode!= "USA") {
                echo $this->renderView('backOffice/vpn_error.html.twig');
                die();
            } 
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 2013-05-01
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 2020-03-06
    相关资源
    最近更新 更多