除非您在localhost中,否则拒绝访问Symfony方法

时间:2018-04-17 07:14:13

标签: php symfony security localhost

我想知道如何拒绝访问到控制器方法它没有从localhost 调用它。例如,我希望只有在本地主机上时才允许访问此URL __all__

我在doc https://symfony.com/doc/3.2/security.html

上找不到任何内容

2 个答案:

答案 0 :(得分:2)

查看access_control documentation。您可以使用allow_if键并执行以下操作:

access_control:
    - path: ^/usermanagement
      allow_if: "request.getHost() == 'localhost'"

答案 1 :(得分:2)

首先,fxbt的解决方案很棒。

但您也可以使用security.yaml文件中的防火墙配置来执行此操作:https://symfony.com/doc/3.2/security/firewall_restriction.html

# app/config/security.yml

# ...
security:
    firewalls:
        # This is a custom firewall area and may conflict with your existing firewall
        other_secured_area:
            host: ^localhost$
            pattern: ^/usermanagement

另一个解决方案是直接在控制器中执行:

public function userManagement(Request $request)
{
    if ($request->getHost() !== 'localhost') {
        throw new $this->createAccessDeniedException();
    }
}

在任何情况下都要小心,因为主机安全性可能不是最好的安全性(在大多数情况下可以从客户端操纵主机)。