Mich
Mich

Reputation: 65

Deny access in Symfony method unless you are in localhost

I want to know how to deny the access to a controller method that it isn't being called from localhost. For example, I would like to allow the access to this URL www.myweb.com/usermanagement only if you are on localhost.

I didn't find anything on doc https://symfony.com/doc/3.2/security.html

Upvotes: 0

Views: 1129

Answers (2)

Nek
Nek

Reputation: 3115

First, the solution of fxbt is great.

But you can also do it by using the firewall configuration in security.yaml file: 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

Another solution is to do it directly in the controller:

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

In any case by careful because host security may not be the best security (it's possible to manipulate the host from the client in most cases).

Upvotes: 2

fxbt
fxbt

Reputation: 2596

Look in the access_control documentation. You can use the allow_if key and do something like this:

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

Upvotes: 3

Related Questions