在验证用户与 Symfony 4 和 FOSUserBundle 连接后重定向用户

你好世界 !

我是一名 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 地址。感谢您的关注。


跃然一笑
浏览 170回答 1
1回答

jeck猫

我找到了解决方案,但我知道这不是最好的,但目前它让我满意。我已经编辑了denyAccessUnlessGranted() 方法,并使用回显强制显示错误 我的解决方案是这样的:    /**     * 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();            }         }    }
打开App,查看更多内容
随时随地看视频慕课网APP