如何使用 Symfony 5 通过端口限制对特定路由的访问?

How to restrict access to certain route by port with Symfony 5?

我们的网络服务器正在侦听 80 和 8080 端口,我希望特定路由仅通过端口 8080 可用,但拒绝所有尝试使用端口 80 访问该路由的用户访问。

我的 routes.yaml

中有一些路线
testing-logging:
  path: /testing/logging
  controller: Test\Infrastructure\API\HTTP\Technical\LoggingController::handle
  methods: [GET]

healthcheck:
  path: /healthcheck
  controller: Test\API\HTTP\Technical\HealthcheckController::handle
  methods: [GET]

当然还有更多的路线,但它们就像这些。

这是一个微服务,所以没有任何用户。

我想通过自定义端口限制某些路由的访问。当然,其他路由必须像以前一样使用标准端口。

我尝试使用安全性:

security:
    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    providers:
        in_memory: { memory: null }
    firewalls:
        dev:
            security: true
            anonymous: ~
            methods: [POST]
        main:
            anonymous: lazy
    access_control:
        - { path: ^/healthcheck, roles: IS_AUTHENTICATED_ANONYMOUSLY, port: 8080 }

只需为端口 80 添加另一个 access_control 规则。

access_control:
        - { path: ^/healthcheck, roles: IS_AUTHENTICATED_ANONYMOUSLY, port: 8080 }
        - { path: ^/healthcheck, roles: ROLE_ADMIN, port: 80 }

由于您没有任何身份验证机制,因此没有用户会拥有 ROLE_ADMIN。因此,任何试图在端口 80 上访问 ^/healthcheck 的用户都将被拒绝访问。