Search code examples
phpsymfonysymfony-security

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


Our webserver is listening 80 and 8080 ports, and I want a specific route to be available only through port 8080, but to deny access to all users that attempt to access that route using port 80.

I have some routes in my 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]

There are a little more routes of course, but they are like these ones.

It's a microservice, so there are no any users.

I want to restrict access for some routes by custom port. Of course, others routes must work as before with standard port.

I tried to use security:

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 }

Solution

  • Just add another access_control rule for port 80.

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

    Since you do not have any authentication mechanism, no user will have ROLE_ADMIN. Thus, any user attempting to access ^/healthcheck on port 80 will have their access denied.