为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
跃然一笑 2022-05-27 10:18:37
你好世界 !我是一名 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 地址。感谢您的关注。
查看完整描述

1 回答

?
jeck猫

TA贡献1909条经验 获得超7个赞

我找到了解决方案,但我知道这不是最好的,但目前它让我满意。我已经编辑了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();

            } 

        }

    }


查看完整回答
反对 回复 2022-05-27
  • 1 回答
  • 0 关注
  • 145 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号